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

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

export interface RawPackageFeature {
  package_key: string;
  package_value: string;  // "0" | "1"
}

export interface RawPackage {
  id: number;
  name: string;
  price: number;
  storage_type: number;
  image: string;
  time: string;
  type: string;     // "Month" | "Year"
  ads_free: number;
  download_content: number;
  background_play: number;
  web_product_package: string;
  status: number;
  created_at: string;
  is_buy: number;   // 1 = currently subscribed
  data: RawPackageFeature[];
}

export interface PackageResponse {
  status: number;
  message: string;
  result: RawPackage[];
}

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

export interface PackageFeature {
  key: string;
  enabled: boolean;
}

export interface Package {
  id: string;
  name: string;
  price: number;
  image: string;
  duration: string;       // e.g. "1 Month", "3 Months", "1 Year"
  durationUnit: string;   // "Month" | "Year"
  durationCount: number;
  adsFree: boolean;
  downloadContent: boolean;
  backgroundPlay: boolean;
  isOwned: boolean;
  isBestValue: boolean;   // computed
  features: PackageFeature[];
  monthlyEquivalent: string; // e.g. "₹1/mo"
}

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

export const packageService = {
  getPackages: (): Promise<PackageResponse> =>
    apiClient.post(API_ENDPOINTS.GET_PACKAGE, {}).then((r) => r.data),

  mapPackage: (raw: RawPackage, allPackages: RawPackage[], currencyCode = "$"): Package => {
    const count = parseInt(raw.time) || 1;
    const months = raw.type === "Year" ? count * 12 : count;
    const perMonth = raw.price / months;

    // Best value = lowest monthly equivalent
    const allPerMonth = allPackages.map((p) => {
      const c = parseInt(p.time) || 1;
      const m = p.type === "Year" ? c * 12 : c;
      return p.price / m;
    });
    const minPerMonth = Math.min(...allPerMonth);
    const isBestValue = perMonth === minPerMonth && allPackages.length > 1;

    const durationLabel = count === 1
      ? `1 ${raw.type}`
      : `${count} ${raw.type}s`;

    return {
      id: String(raw.id),
      name: raw.name,
      price: raw.price,
      image: raw.image,
      duration: durationLabel,
      durationUnit: raw.type,
      durationCount: count,
      adsFree: raw.ads_free === 1,
      downloadContent: raw.download_content === 1,
      backgroundPlay: raw.background_play === 1,
      isOwned: raw.is_buy === 1,
      isBestValue,
      features: raw.data.map((f) => ({
        key: f.package_key,
        enabled: f.package_value === "1",
      })),
      monthlyEquivalent: perMonth < 1
        ? `${currencyCode}${perMonth.toFixed(2)}/mo`
        : `${currencyCode}${Math.round(perMonth)}/mo`,
    };
  },
};
