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

/* ── Constants ─────────────────────────────────────────────────────────────── */

export const DEFAULT_AVATAR =
  "https://dttube.divinetechs.com/public/assets/imgs/default.png";
export const isDefaultAvatar = (url: string) => !url || url === DEFAULT_AVATAR;

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

export interface RawComment {
  id: number;
  comment_id: number;   // 0 = top-level, N = reply
  user_id: number;
  content_type: number;
  content_id: number;
  episode_id: number;
  comment: string;
  status: number;
  created_at: string;
  updated_at: string;
  channel_name: string;
  full_name: string;
  email: string;
  image: string;
  is_reply: number;     // 0 | 1
  total_reply: number;
}

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

export interface AddCommentResponse {
  status: number;
  message: string;
  result: unknown[];
}

/* ── Mapped type ───────────────────────────────────────────────────────────── */

export interface CommentItem {
  id: string;
  parentId: string;     // "0" = top-level
  userId: string;
  channelName: string;
  avatar: string;       // "" if default
  comment: string;
  createdAt: string;
  isReply: boolean;
  totalReply: number;
  isOptimistic?: boolean;  // locally inserted, not yet confirmed by API
}

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

export const commentService = {
  getComments: (params: {
    contentType: number;
    contentId: string;
    episodeId?: number;
    pageNo: number;
  }): Promise<CommentListResponse> =>
    apiClient
      .post(API_ENDPOINTS.GET_COMMENT, {
        content_type: params.contentType,
        content_id: params.contentId,
        episode_id: params.episodeId ?? 0,
        page_no: params.pageNo,
      })
      .then((r) => r.data),

  addComment: (params: {
    contentType: number;
    contentId: string;
    comment: string;
    commentId?: number;   // 0 = new, N = reply
    episodeId?: number;
  }): Promise<AddCommentResponse> =>
    apiClient
      .post(API_ENDPOINTS.ADD_COMMENT, {
        content_type: params.contentType,
        content_id: params.contentId,
        comment: params.comment,
        comment_id: params.commentId ?? 0,
        episode_id: params.episodeId ?? 0,
      })
      .then((r) => r.data),

  deleteComment: (commentId: string): Promise<{ status: number; message: string }> =>
    apiClient
      .post(API_ENDPOINTS.DELETE_COMMENT, { comment_id: commentId })
      .then((r) => r.data),

  editComment: (params: {
    commentId: string;
    comment: string;
  }): Promise<{ status: number; message: string }> =>
    apiClient
      .post(API_ENDPOINTS.EDIT_COMMENT, {
        comment_id: params.commentId,
        comment:    params.comment,
      })
      .then((r) => r.data),

  getReplies: (commentId: string): Promise<CommentListResponse> =>
    apiClient
      .post(API_ENDPOINTS.GET_REPLY_COMMENT, { comment_id: commentId })
      .then((r) => r.data),

  mapComment: (raw: RawComment): CommentItem => ({
    id: String(raw.id),
    parentId: String(raw.comment_id),
    userId: String(raw.user_id),
    channelName: raw.channel_name || raw.full_name || "User",
    avatar: isDefaultAvatar(raw.image) ? "" : raw.image,
    comment: raw.comment,
    createdAt: formatRelativeDate(raw.created_at),
    isReply: raw.is_reply === 1,
    totalReply: raw.total_reply,
  }),
};
