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

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

export interface RawSubscriber {
  id: number;
  channel_id: string;
  channel_name: string;
  full_name: string;
  email: string;
  country_code: string;
  mobile_number: string;
  country_name: string;
  type: number;               // 1 = user, 2 = creator/channel
  image: string;              // avatar
  cover_img: string;          // banner
  description: string;
  website: string;
  facebook_url: string;
  instagram_url: string;
  twitter_url: string;
  is_account_verify: number;  // 1 = verified
  total_subscriber: number;
  status: number;
  created_at: string;
  is_buy: number;
}

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

/* ── Default image sentinel ────────────────────────────────────────────────── */

const DEFAULT_IMGS = new Set([
  "https://dttube.divinetechs.com/public/assets/imgs/default.png",
  "https://dttube.divinetechs.com/public/assets/imgs/no_img.png",
]);

export function isDefaultImg(url: string) {
  return !url || DEFAULT_IMGS.has(url);
}

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

export interface SubscriberChannel {
  id: string;
  channelId: string;
  channelName: string;
  fullName: string;
  avatar: string;           // "" if default
  coverImg: string;         // "" if default
  description: string;
  website: string;
  facebook: string;
  instagram: string;
  twitter: string;
  isVerified: boolean;
  isCreator: boolean;       // type === 2
  totalSubscribers: string; // formatted
  totalSubscribersRaw: number;
  countryName: string;
  subscribed: boolean;      // local toggle state
}

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

export const subscriberService = {
  getSubscribeList: (pageNo: number): Promise<SubscribeListResponse> =>
    apiClient
      .post(API_ENDPOINTS.GET_SUBSCRIBE_LIST, { page_no: pageNo })
      .then((r) => r.data),

  mapChannel: (raw: RawSubscriber): SubscriberChannel => ({
    id: String(raw.id),
    channelId: raw.channel_id,
    channelName: raw.channel_name,
    fullName: raw.full_name,
    avatar: isDefaultImg(raw.image) ? "" : raw.image,
    coverImg: isDefaultImg(raw.cover_img) ? "" : raw.cover_img,
    description: raw.description || "",
    website: raw.website || "",
    facebook: raw.facebook_url || "",
    instagram: raw.instagram_url || "",
    twitter: raw.twitter_url || "",
    isVerified: raw.is_account_verify === 1,
    isCreator: raw.type === 2,
    totalSubscribers: formatlike(raw.total_subscriber),
    totalSubscribersRaw: raw.total_subscriber,
    countryName: raw.country_name || "",
    subscribed: true,
  }),
};
