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

export interface RawVideoListItem {
  id: number;
  content_type: number;
  channel_id: string;
  category_id: number;
  title: string;
  description: string;
  landscape_img: string;
  portrait_img: string;
  content: string;
  content_duration: number;
  content_upload_type: string;
  is_rent: number;
  rent_price: number;
  total_view: number;
  total_like: number;
  total_dislike: number;
  is_like: number;
  is_comment: number;
  is_download: number;
  status: number;
  created_at: string;
  user_id: number;
  channel_name: string;
  channel_image: string;
  category_name: string;
  language_name: string;
  is_subscribe: number;
  total_comment: number;
  total_subscriber: number;
  is_user_like_dislike: number;
  is_buy: number;
  stop_time: number;
}

export interface VideoListResponse {
  status: number;
  message: string;
  result: RawVideoListItem[];
  total_rows: number;
  total_page: number;
  current_page: number;
  more_page: boolean;
}

export interface FetchVideoListParams {
  categoryId: number;
  pageNo: number;
}

function contentTypeToMediaType(ct: number): "video" | "short" | "music" {
  if (ct === 2) return "short";
  if (ct === 3) return "music";
  return "video";
}

export const videoListService = {
  getVideoList: (params: FetchVideoListParams): Promise<VideoListResponse> =>
    apiClient
      .post(API_ENDPOINTS.VIDEO.LIST, {
        is_home_page: params.categoryId == 0 ? 1 : 0,
        category_id: params.categoryId,
        page_no: params.pageNo,
      })
      .then((r) => r.data),

  mapVideo: (raw: RawVideoListItem): VideoItem => ({
    id: String(raw.id),
    title: raw.title,
    thumbnail: raw.landscape_img,
    duration: raw.content_duration > 0 ? formatDuration(raw.content_duration) : "",
    views: formatViews(raw.total_view),
    uploadedAt: formatRelativeDate(raw.created_at),
    channelName: raw.channel_name,
    channelAvatar: raw.channel_image,
    category: raw.category_name,
    type: contentTypeToMediaType(raw.content_type),
    isPremium: raw.is_rent === 1,
  }),
};
