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

export interface RawReelItem {
  id: number;
  content_type: number;
  title: string;
  portrait_img: string;
  landscape_img: string;
  content: string;
  content_upload_type: string;
  total_like: number;
  total_dislike: number;
  total_view: number;
  total_comment: number;
  is_like: number;
  is_comment: number;
  is_download: number;
  is_user_like_dislike: number;
  is_subscribe: number;
  channel_name: string;
  channel_image: string;
  channel_id?: string;
  created_at: string;
  status: number;
  user_id?: number;
}

export interface MappedReel {
  id: string;
  contentType: number;
  caption: string;
  likes: string;
  totalLikeCount: number;
  totalDislikeCount: number;
  isUserLikeDislike: number;
  isLike: number;
  image: string;
  hue: number;
  channelName: string;
  channelImage: string;
  channelId: string;
  channelUserId: string;
  videoUrl: string;
  totalComments: number;
  totalView: string;
  /* ReelsPage-specific aliases */
  creator: string;
  initial: string;
  sound: string;
  comments: string;
}

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

export const reelsListService = {
  getReelsList: (pageNo: number): Promise<ReelsListResponse> =>
    apiClient
      .post(API_ENDPOINTS.GET_REELS_LIST, { page_no: pageNo })
      .then((r) => r.data),

  mapReel: (raw: RawReelItem): MappedReel => ({
    id: String(raw.id),
    contentType: raw.content_type,
    caption: raw.title,
    likes: formatlike(raw.total_like),
    totalLikeCount: raw.total_like,
    totalDislikeCount: raw.total_dislike,
    isUserLikeDislike: raw.is_user_like_dislike,
    isLike: raw.is_like,
    image: raw.portrait_img,
    hue: (raw.id * 47) % 360,
    totalView: formatViews(raw.total_view),
    channelName: raw.channel_name,
    channelImage: raw.channel_image,
    channelId: raw.channel_id ?? "",
    channelUserId: raw.user_id ? String(raw.user_id) : "",
    videoUrl: raw.content,
    totalComments: raw.total_comment,
    creator: raw.channel_name,
    initial: (raw.channel_name[0] ?? "?").toUpperCase(),
    sound: raw.title.slice(0, 40) || "Original Sound",
    comments: String(raw.total_comment),
  }),
};
