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

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

export interface RawFeedContent {
  id: number;
  feed_id: number;
  content_type: number; // 1 = image, 2 = video
  image: string;
  video: string;
  status: number;
  created_at: string;
}

export interface RawHashtag {
  id: number;
  name: string;
  total_used: number;
  status: number;
  created_at: string;
}

export interface RawFeedPost {
  id: number;
  type?: number;
  channel_id: string | number;
  hashtag_id: string;
  title?: string;
  description: string;
  /* list feed fields */
  is_like?: number;
  is_comment?: number;
  is_subscriber?: number;
  /* detail feed fields (new API) */
  is_user_like?: number;
  is_follow?: number;
  is_verified?: number;
  total_like: number;
  total_comment: number;
  status: number;
  created_at: string;
  updated_at: string;
  feed_content: RawFeedContent[];
  hastegs?: RawHashtag[];   // list API
  hasteg?: RawHashtag[];    // detail API
  user_id: number;
  channel_name: string;
  channel_image?: string;
  full_name?: string;
  profile_img?: string;
  is_buy?: number;
}

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

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

export interface FeedMediaItem {
  id: string;
  type: "image" | "video";
  image: string;
  video: string;
}

export interface FeedHashtag {
  id: number;
  name: string;
}

export interface FeedPost {
  id: string;
  userId: string;
  userType: number;
  channelId: string;
  title: string;
  isVerified: boolean;
  channelName: string;
  fullName: string;
  profileImg: string;
  description: string;
  isLiked: boolean;
  canComment: boolean;
  totalLikes: number;
  totalComments: number;
  createdAt: string;
  isSubscriber: boolean;
  media: FeedMediaItem[];
  hashtags: FeedHashtag[];
}

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

/* ── Feed comment types ────────────────────────────────────────────────────── */

export interface RawFeedComment {
  id: number;
  feed_id: number;
  user_id: number;
  comment: string;
  comment_id: number;
  created_at: string;
  channel_name: string;
  full_name: string;
  image: string;
  total_reply: number;
}

export interface FeedComment {
  id: string;
  feedId: string;
  userId: string;
  parentId: string;
  channelName: string;
  avatar: string;
  comment: string;
  createdAt: string;
  totalReply: number;
}

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

export const feedService = {
  getFeed: (pageNo: number): Promise<FeedResponse> =>
    apiClient
      .post(API_ENDPOINTS.GET_FEED, { page_no: pageNo })
      .then((r) => r.data),

  likeUnlikeFeed: (feedId: string): Promise<{ status: number; message: string }> =>
    apiClient
      .post(API_ENDPOINTS.FEED.LIKE, { feed_id: feedId })
      .then((r) => r.data),

  getFeedComments: async (feedId: string): Promise<FeedComment[]> => {
    const res = await apiClient.post(API_ENDPOINTS.FEED.GET_COMMENTS, { feed_id: feedId });
    const raw: RawFeedComment[] = res.data?.result ?? [];
    return raw.map((r) => ({
      id:          String(r.id),
      feedId:      String(r.feed_id),
      userId:      String(r.user_id),
      parentId:    String(r.comment_id ?? "0"),
      channelName: r.channel_name || r.full_name || "User",
      avatar:      r.image ?? "",
      comment:     r.comment,
      createdAt:   formatRelativeDate(r.created_at),
      totalReply:  r.total_reply ?? 0,
    }));
  },

  addFeedComment: (params: {
    feedId: string;
    comment: string;
    commentId?: string;
  }): Promise<{ status: number; message: string }> =>
    apiClient
      .post(API_ENDPOINTS.FEED.ADD_COMMENT, {
        feed_id:    params.feedId,
        comment:    params.comment,
        comment_id: params.commentId ?? "0",
      })
      .then((r) => r.data),

  getFeedDetail: (feedId: string): Promise<{ status: number; result: RawFeedPost[] | RawFeedPost }> =>
    apiClient
      .post(API_ENDPOINTS.FEED.GET_DETAIL, { feed_id: feedId })
      .then((r) => r.data),

  mapPost: (raw: RawFeedPost): FeedPost => ({
    id: String(raw.id),
    userId: String(raw.user_id),
    userType: raw.type ?? 1,
    channelId: String(raw.channel_id),
    title: raw.title || "",
    isVerified: raw.is_verified === 1,
    channelName: raw.channel_name,
    fullName: raw.full_name || raw.channel_name || "",
    profileImg: raw.profile_img || raw.channel_image || "",
    description: raw.description || "",
    isLiked: (raw.is_user_like ?? raw.is_like ?? 0) === 1,
    canComment: (raw.is_comment ?? 1) === 1,
    totalLikes: raw.total_like,
    totalComments: raw.total_comment,
    createdAt: formatRelativeDate(raw.created_at),
    isSubscriber: (raw.is_follow ?? raw.is_subscriber ?? 0) === 1,
    media: (raw.feed_content ?? []).map((fc) => ({
      id: String(fc.id),
      type: fc.content_type === 2 ? "video" : "image",
      image: fc.image,
      video: fc.video,
    })),
    hashtags: (raw.hasteg ?? raw.hastegs ?? []).map((h) => ({ id: h.id, name: h.name })),
  }),
  getFeedReplies: async (commentId: string): Promise<FeedComment[]> => {
    const res = await apiClient.post(API_ENDPOINTS.FEED_COMMENT.GET_REPLIES, { comment_id: commentId });
    const raw: RawFeedComment[] = res.data?.result ?? [];
    return raw.map((r) => ({
      id:          String(r.id),
      feedId:      String(r.feed_id),
      userId:      String(r.user_id),
      parentId:    commentId,
      channelName: r.channel_name || r.full_name || "User",
      avatar:      r.image ?? "",
      comment:     r.comment,
      createdAt:   formatRelativeDate(r.created_at),
      totalReply:  0,
    }));
  },

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

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

  deleteFeed: (feedId: string): Promise<{ status: number; message: string }> =>
    apiClient
      .post(API_ENDPOINTS.FEED_MGMT.DELETE, { feed_id: feedId })
      .then((r) => r.data),

  reportFeed: (params: {
    reportUserId: string;
    feedId: string;
    message: string;
  }): Promise<{ status: number; message: string }> =>
    apiClient
      .post(API_ENDPOINTS.FEED_MGMT.REPORT, {
        report_user_id: params.reportUserId,
        feed_id:        params.feedId,
        message:        params.message,
      })
      .then((r) => r.data),
};

export { formatlike };
