import apiClient from "@/lib/axiosClient";
import { API_ENDPOINTS } from "@/lib/apiEndpoints";
import { formatViews, formatDuration } from "@/utils/format";

export interface SearchHistoryItem {
  id: string;
  title: string;
}

export interface RawSearchItem {
  id: number;
  content_type: number;
  title: string;
  portrait_img?: string;
  landscape_img?: string;
  content?: string;
  content_upload_type?: string;
  content_duration?: number;
  channel_name?: string;
  channel_image?: string;
  total_view?: number;
  total_like?: number;
  total_comment?: number;
  is_like?: number;
  is_comment?: number;
  is_subscribe?: number;
  user_id?: number;
  is_buy?: number;
}

export interface SearchItem {
  id: string;
  contentType: number;
  title: string;
  thumbnail: string;
  landscapeImg: string;
  audioUrl: string;
  channelName: string;
  channelImage: string;
  duration: string;
  views: string;
}

export interface SearchResponse {
  status: number;
  message: string;
  result?: RawSearchItem[];
  video?: RawSearchItem[];
  music?: RawSearchItem[];
}

function mapItem(raw: RawSearchItem): SearchItem {
  return {
    id: String(raw.id),
    contentType: raw.content_type,
    title: raw.title || "",
    thumbnail: raw.portrait_img || raw.landscape_img || "",
    landscapeImg: raw.landscape_img || raw.portrait_img || "",
    audioUrl: raw.content || "",
    channelName: raw.channel_name || "",
    channelImage: raw.channel_image || "",
    duration: raw.content_duration ? formatDuration(raw.content_duration) : "",
    views: formatViews(raw.total_view || 0),
  };
}

export const searchService = {
  search: async (name: string): Promise<{ videos: SearchItem[]; music: SearchItem[] }> => {
    const [videoRes, musicRes] = await Promise.all([
      apiClient.post(API_ENDPOINTS.SEARCH_CONTENT, { name, type: 1 }).then((r) => r.data as SearchResponse),
      apiClient.post(API_ENDPOINTS.SEARCH_CONTENT, { name, type: 2 }).then((r) => r.data as SearchResponse),
    ]);

    const rawVideos = videoRes.video ?? videoRes.result ?? [];
    const rawMusic = musicRes.music ?? musicRes.result ?? [];

    return {
      videos: rawVideos.map(mapItem),
      music: rawMusic.map(mapItem),
    };
  },

  getSearchHistory: (): Promise<SearchHistoryItem[]> =>
    apiClient
      .post(API_ENDPOINTS.SEARCH_HISTORY.GET, {})
      .then((r) => {
        const raw = r.data?.result ?? [];
        return raw.map((item: { id: number | string; title: string }) => ({
          id: String(item.id),
          title: item.title,
        }));
      }),

  removeSearchHistoryItem: (id: string): Promise<void> =>
    apiClient
      .post(API_ENDPOINTS.SEARCH_HISTORY.REMOVE, { id })
      .then(() => {}),
};
