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

/* ── Shared content detail ──────────────────────────────────────────────────── */

export interface ContentDetail {
  id: string;
  contentType: number;
  title: string;
  description: string;
  thumbnail: string;
  landscapeImg: string;
  audioUrl: string;
  channelName: string;
  channelImage: string;
  channelId: string;
  channelUserId: string;
  categoryName: string;
  languageName: string;
  views: string;
  totalLike: number;
  totalDislike: number;
  totalComment: number;
  totalSubscribers: number;
  isLike: number;
  isComment: number;
  isDownload: number;
  isSubscribe: number;
  isUserLikeDislike: number;
  isBuy: number;
  duration: string;
  createdAt: string;
}

export interface Episode {
  id: string;
  podcastsId: string;
  name: string;
  description: string;
  thumbnail: string;
  landscapeImg: string;
  audioUrl: string;
  uploadType: string;
  views: number;
  totalLike: number;
  isLike: number;
  isComment: number;
  isDownload: number;
  isUserLikeDislike: number;
  isBuy: number;
  stopTime: number;
  podcastsName: string;
}

export interface RelatedMusic extends ContentDetail {}

function mapDetail(raw: Record<string, unknown>): ContentDetail {
  return {
    id: String(raw.id as number),
    contentType: raw.content_type as number,
    title: raw.title as string || "",
    description: raw.description as string || "",
    thumbnail: raw.portrait_img as string || "",
    landscapeImg: raw.landscape_img as string || "",
    audioUrl: raw.content as string || "",
    channelName: raw.channel_name as string || "",
    channelImage: raw.channel_image as string || "",
    channelId: raw.channel_id as string || "",
    channelUserId: String(raw.user_id as number || 0),
    categoryName: raw.category_name as string || "",
    languageName: raw.language_name as string || "",
    views: formatViews(raw.total_view as number || 0),
    totalLike: raw.total_like as number || 0,
    totalDislike: raw.total_dislike as number || 0,
    totalComment: raw.total_comment as number || 0,
    totalSubscribers: raw.total_subscriber as number || 0,
    isLike: raw.is_like as number || 0,
    isComment: raw.is_comment as number || 0,
    isDownload: raw.is_download as number || 0,
    isSubscribe: raw.is_subscribe as number || 0,
    isUserLikeDislike: raw.is_user_like_dislike as number || 0,
    isBuy: raw.is_buy as number || 0,
    duration: raw.content_duration ? formatDuration(raw.content_duration as number) : "",
    createdAt: raw.created_at ? formatRelativeDate(raw.created_at as string) : "",
  };
}

function mapEpisode(raw: Record<string, unknown>): Episode {
  return {
    id: String(raw.id as number),
    podcastsId: String(raw.podcasts_id as number),
    name: raw.name as string || "",
    description: raw.description as string || "",
    thumbnail: raw.portrait_img as string || "",
    landscapeImg: raw.landscape_img as string || "",
    audioUrl: raw.episode_audio as string || "",
    uploadType: raw.episode_upload_type as string || "",
    views: raw.total_view as number || 0,
    totalLike: raw.total_like as number || 0,
    isLike: raw.is_like as number || 0,
    isComment: raw.is_comment as number || 0,
    isDownload: raw.is_download as number || 0,
    isUserLikeDislike: raw.is_user_like_dislike as number || 0,
    isBuy: raw.is_buy as number || 0,
    stopTime: raw.stop_time as number || 0,
    podcastsName: raw.podcasts_name as string || "",
  };
}

export const contentDetailService = {
  getDetail: async (contentType: number, contentId: string): Promise<ContentDetail | null> => {
    const res = await apiClient.post(API_ENDPOINTS.CONTENT.DETAIL, {
      content_type: contentType,
      content_id: contentId,
    });
    const raw = res.data?.result?.[0];
    return raw ? mapDetail(raw as Record<string, unknown>) : null;
  },

  getEpisodes: async (podcastsId: string): Promise<Episode[]> => {
    const res = await apiClient.post(API_ENDPOINTS.CONTENT.EPISODES, { podcasts_id: podcastsId });
    return (res.data?.result ?? []).map((r: Record<string, unknown>) => mapEpisode(r));
  },

  getRelatedMusic: async (contentId: string): Promise<RelatedMusic[]> => {
    const res = await apiClient.post(API_ENDPOINTS.CONTENT.RELATED_MUSIC, { content_id: contentId });
    return (res.data?.result ?? []).map((r: Record<string, unknown>) => mapDetail(r));
  },
};
