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

/** content_storage_type values from the API */
export enum ContentStorageType {
  ServerUrl = 1,   // direct MP4 / HLS hosted on DTTube server
  ExternalUrl = 2, // external CDN / streaming service URL
  YouTube = 3,     // YouTube watch/embed URL
}

export interface VideoDetail {
  id: string;
  title: string;
  description: string;
  thumbnail: string;
  portraitImg: string;
  videoUrl: string;
  contentUploadType: string;
  contentType: number;
  contentStorageType: ContentStorageType;
  durationMs: number;
  views: string;
  totalLike: number;
  totalDislike: number;
  totalComment: number;
  channelName: string;
  channelImage: string;
  channelId: string;
  channelUserId: string;  // user_id of channel owner — for subscribe API
  categoryId: number;
  categoryName: string;
  languageName: string;
  uploadedAt: string;
  isLike: number;
  isComment: number;
  isDownload: number;
  isUserDownload: number;
  isRent: number;
  rentPrice: number;
  totalSubscribers: number;
  isSubscribe: number;
  isUserLikeDislike: number;
  isBuy: number;
  stopTime: number;

}

interface RawVideoDetail {
  id: number;
  content_type: number;
  content_storage_type: number;
  channel_id: string;
  category_id: number;
  language_id: number;
  title: string;
  description: string;
  landscape_img: string;
  portrait_img: string;
  content: string;
  content_upload_type: string;
  content_duration: number;
  is_rent: number;
  rent_price: number;
  is_like: number;
  is_comment: number;
  is_download: number;
  is_user_download: number;
  total_view: number;
  total_like: number;
  total_dislike: number;
  total_comment: number;
  created_at: string;
  channel_name: string;
  channel_image: string;
  category_name: string;
  language_name: string;
  is_subscribe: number;
  total_subscriber: number;
  is_user_like_dislike: number;
  is_buy: number;
  stop_time: number;
  playlist_image: string[];
  user_id?: number;
}

export interface VideoDetailResponse {
  status: number;
  message: string;
  result: RawVideoDetail[];   // API returns an array — take result[0]
}

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

interface RawVideoListItem {
  id: number;
  content_type: number;
  channel_id: string;
  category_id: number;
  language_id: number;
  hashtag_id: string;
  title: string;
  description: string;
  portrait_img_storage_type: number;
  portrait_img: string;
  landscape_img_storage_type: number;
  landscape_img: string;
  content_storage_type: number;
  content_upload_type: string;
  content: 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;
  playlist_type: number;
  total_watch_time: string;
  status: number;
  created_at: string;
  updated_at: string;
  user_id: number;
  channel_name: string;
  channel_image: string;
  category_name: string;
  language_name: string;
  is_subscribe: number;
  total_comment: number;
  is_user_like_dislike: number;
  total_subscriber: number;
  is_buy: number;
  stop_time: number;
}

export const videoDetailService = {
  getVideoDetail: (videoId: string): Promise<VideoDetailResponse> =>
    apiClient
      .post(API_ENDPOINTS.VIDEO.DETAIL, {
        content_id: videoId,
        content_type: 1,
      })
      .then((r) => r.data),

  getRelatedVideos: (contentId: string): Promise<RelatedVideosResponse> =>
    apiClient
      .post(API_ENDPOINTS.VIDEO.RELATED, {
        content_id: contentId,
      })
      .then((r) => r.data),

  mapVideoDetail: (raw: RawVideoDetail): VideoDetail => ({
    id: String(raw.id),
    title: raw.title,
    description: raw.description,
    thumbnail: raw.landscape_img || raw.portrait_img,
    portraitImg: raw.portrait_img,
    videoUrl: raw.content,
    contentUploadType: raw.content_upload_type,
    contentType: raw.content_type,
    contentStorageType: raw.content_storage_type as ContentStorageType,
    durationMs: raw.content_duration,
    views: formatViews(raw.total_view),
    totalLike: raw.total_like,
    totalDislike: raw.total_dislike,
    totalComment: raw.total_comment,
    channelName: raw.channel_name,
    channelImage: raw.channel_image,
    channelId: raw.channel_id,
    channelUserId: raw.user_id ? String(raw.user_id) : raw.channel_id,
    categoryId: raw.category_id,
    categoryName: raw.category_name,
    languageName: raw.language_name,
    uploadedAt: formatRelativeDate(raw.created_at),
    isLike: raw.is_like,
    isComment: raw.is_comment,
    isDownload: raw.is_download,
    isUserDownload: raw.is_user_download ?? 0,
    isRent: raw.is_rent,
    rentPrice: raw.rent_price,
    totalSubscribers: raw.total_subscriber,
    isSubscribe: raw.is_subscribe,
    isUserLikeDislike: raw.is_user_like_dislike,
    isBuy: raw.is_buy,
    stopTime: raw.stop_time,
  }),

  mapRelatedVideo: (raw: RawVideoListItem): VideoItem => ({
    id: String(raw.id),
    title: raw.title,
    thumbnail: raw.landscape_img || raw.portrait_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: raw.content_type === 2 ? "short" : raw.content_type === 3 ? "music" : "video",
    isPremium: raw.is_rent === 1,
  }),
};
