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

/* ── Raw API types ─────────────────────────────────────────────────────────── */

export interface RawRentItem {
  id: number;
  content_type: number;
  channel_id: string;
  category_id: number;
  language_id: number;
  title: string;
  description: string;
  portrait_img: string;
  landscape_img: string;
  content: string;
  content_upload_type: string;
  content_duration: number;
  is_rent: number;
  rent_price: number;
  rent_day: number;
  is_comment: number;
  is_download: number;
  is_like: number;
  total_view: number;
  total_like: number;
  total_dislike: number;
  status: number;
  created_at: string;
  updated_at: string;
  user_id: number;
  channel_name: string;
  channel_image: string;
  category_name: string;
  language_name: string;
  is_user_like_dislike: number;
  is_subscribe: number;
  is_rent_buy: number;  // 1 = already purchased/rented
  is_buy: number;
}

export interface RawRentSection {
  id: number;
  title: string;
  category_id: number;
  no_of_content: number;
  view_all: number;
  sort_order: number;
  status: number;
  created_at: string;
  data: RawRentItem[];
}

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

/* ── Mapped types ──────────────────────────────────────────────────────────── */

export interface RentItem {
  id: string;
  contentType: number;
  title: string;
  description: string;
  thumbnail: string;    // landscape_img
  portraitImg: string;
  videoUrl: string;             // raw.content  — the actual playback URL
  contentUploadType: string;    // raw.content_upload_type  e.g. "youtube" | "server"
  duration: string;
  durationMs: number;
  views: string;
  likes: string;
  totalLike: number;
  totalDislike: number;
  isUserLikeDislike: number;
  uploadedAt: string;
  channelName: string;
  channelImage: string;
  channelId: string;
  channelUserId: string;
  category: string;
  language: string;
  rentPrice: number;
  rentDay: number;
  isOwned: boolean;     // is_rent_buy === 1
  isDownload: boolean;
  canComment: boolean;
  isSubscribed: boolean;
}

export interface RentSection {
  id: string;
  title: string;
  viewAll: boolean;
  items: RentItem[];
}

/* ── Service ───────────────────────────────────────────────────────────────── */

export const rentService = {
  getSections: (pageNo: number): Promise<RentSectionResponse> =>
    apiClient
      .post(API_ENDPOINTS.GET_RENT_SECTION, { page_no: pageNo })
      .then((r) => r.data),

  mapItem: (raw: RawRentItem): RentItem => ({
    id: String(raw.id),
    contentType: raw.content_type,
    title: raw.title,
    description: raw.description || "",
    thumbnail: raw.landscape_img,
    portraitImg: raw.portrait_img,
    videoUrl: raw.content,
    contentUploadType: raw.content_upload_type,
    duration: raw.content_duration > 0 ? formatDuration(raw.content_duration) : "",
    durationMs: raw.content_duration,
    views: formatViews(raw.total_view),
    likes: formatlike(raw.total_like),
    totalLike: raw.total_like,
    totalDislike: raw.total_dislike,
    isUserLikeDislike: raw.is_user_like_dislike,
    uploadedAt: formatRelativeDate(raw.created_at),
    channelName: raw.channel_name,
    channelImage: raw.channel_image,
    channelId: raw.channel_id,
    channelUserId: String(raw.user_id),
    category: raw.category_name,
    language: raw.language_name,
    rentPrice: raw.rent_price,
    rentDay: raw.rent_day,
    isOwned: raw.is_rent_buy === 1,
    isDownload: raw.is_download === 1,
    canComment: raw.is_comment === 1,
    isSubscribed: raw.is_subscribe === 1,
  }),

  mapSection: (raw: RawRentSection): RentSection => ({
    id: String(raw.id),
    title: raw.title,
    viewAll: raw.view_all === 1,
    items: raw.data.map(rentService.mapItem),
  }),

  getSectionDetail: async (sectionId: string): Promise<RentSection | null> => {
    const res = await apiClient.post(API_ENDPOINTS.RENT_DETAIL.SECTION, { section_id: sectionId });
    if (res.data?.status !== 200 || !res.data?.result) return null;
    return rentService.mapSection(res.data.result as RawRentSection);
  },

  getByChannel: async (channelId: string): Promise<RentItem[]> => {
    const res = await apiClient.post(API_ENDPOINTS.RENT_DETAIL.BY_CHANNEL, { channel_id: channelId });
    return (res.data?.result ?? []).map(rentService.mapItem);
  },
};
