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

/* ── Payment option types ───────────────────────────────────────────────────── */

export interface RawPaymentOption {
  id: number;
  name: string;
  visibility: string;
  is_live: string;
  key_1: string;
  key_2: string;
  key_3: string;
  key_4: string;
}

export interface PaymentOption {
  id: number;
  name: string;
  displayName: string;
  isLive: boolean;
  publicKey: string;
}

/* ── Transaction types ──────────────────────────────────────────────────────── */

export interface RawTransaction {
  id: number;
  user_id: number;
  package_id?: number;
  content_id?: number;
  price: number;
  coin?: number;
  transaction_id: string;
  description: string;
  status: number;
  created_at: string;
  package_name?: string;
  content_name?: string;
}

export interface Transaction {
  id: string;
  type: "subscription" | "coin" | "rent";
  name: string;
  price: number;
  coin?: number;
  transactionId: string;
  description: string;
  status: number;
  createdAt: string;
}

/* ── Gateway display config ─────────────────────────────────────────────────── */

export const GATEWAY_DISPLAY: Record<string, { label: string; color: string; bg: string }> = {
  paypal:      { label: "PayPal",      color: "#0070ba", bg: "rgba(0,112,186,0.1)"  },
  razorpay:    { label: "Razorpay",    color: "#3395FF", bg: "rgba(51,149,255,0.1)" },
  flutterwave: { label: "Flutterwave", color: "#F5A623", bg: "rgba(245,166,35,0.1)" },
  payumoney:   { label: "PayUMoney",   color: "#1DBF50", bg: "rgba(29,191,80,0.1)"  },
  paytm:       { label: "Paytm",       color: "#00BAF2", bg: "rgba(0,186,242,0.1)"  },
  stripe:      { label: "Stripe",      color: "#635BFF", bg: "rgba(99,91,255,0.1)"  },
  inapppurchage:{ label: "In-App",     color: "var(--accent)", bg: "rgba(var(--accent-rgb),0.1)" },
};

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

export const paymentService = {
  getOptions: async (): Promise<PaymentOption[]> => {
    const res = await apiClient.post(API_ENDPOINTS.PAYMENT.GET_OPTIONS);
    const raw = res.data?.result ?? {};
    return Object.values(raw as Record<string, RawPaymentOption>)
      .filter((o) => o.visibility === "1")
      .map((o) => ({
        id: o.id,
        name: o.name,
        displayName: GATEWAY_DISPLAY[o.name]?.label ?? o.name,
        isLive: o.is_live === "1",
        publicKey: o.key_1,
      }));
  },

  addTransaction: (params: {
    packageId: string; price: number; transactionId: string; description: string;
  }) =>
    apiClient.post(API_ENDPOINTS.PAYMENT.ADD_TRANSACTION, {
      package_id: params.packageId,
      price: params.price,
      transaction_id: params.transactionId,
      description: params.description,
    }).then((r) => r.data),

  addRentTransaction: (params: {
    contentId: string; price: number; transactionId: string; description: string;
  }) =>
    apiClient.post(API_ENDPOINTS.PAYMENT.ADD_RENT_TRANSACTION, {
      content_id: params.contentId,
      price: params.price,
      transaction_id: params.transactionId,
      description: params.description,
    }).then((r) => r.data),

  addCoinTransaction: (params: {
    packageId: string; price: number; coin: number; transactionId: string; description: string;
  }) =>
    apiClient.post(API_ENDPOINTS.PAYMENT.ADD_COIN_TRANSACTION, {
      package_id: params.packageId,
      price: params.price,
      coin: params.coin,
      transaction_id: params.transactionId,
      description: params.description,
    }).then((r) => r.data),

  getTransactions: async (): Promise<Transaction[]> => {
    const res = await apiClient.post(API_ENDPOINTS.PAYMENT.GET_TRANSACTIONS);
    return (res.data?.result ?? []).map((r: RawTransaction) => ({
      id: String(r.id),
      type: "subscription" as const,
      name: r.package_name ?? `Package #${r.package_id}`,
      price: r.price,
      transactionId: r.transaction_id,
      description: r.description,
      status: r.status,
      createdAt: formatRelativeDate(r.created_at),
    }));
  },

  getCoinTransactions: async (): Promise<Transaction[]> => {
    const res = await apiClient.post(API_ENDPOINTS.PAYMENT.GET_COIN_TRANSACTIONS);
    return (res.data?.result ?? []).map((r: RawTransaction) => ({
      id: String(r.id),
      type: "coin" as const,
      name: r.package_name ?? `Coin Pack #${r.package_id}`,
      price: r.price,
      coin: r.coin,
      transactionId: r.transaction_id,
      description: r.description,
      status: r.status,
      createdAt: formatRelativeDate(r.created_at),
    }));
  },

  /* Generate a fake transaction ID for simulated gateway flow */
  generateTxnId: (gateway: string) =>
    `${gateway.toUpperCase()}_${Date.now()}_${Math.random().toString(36).slice(2, 9).toUpperCase()}`,
};
