import { NextResponse } from "next/server";
import { CAM_MODELS, CamModel, getModelAffiliateUrl } from "@/lib/camModels";

export const dynamic = "force-dynamic";
export const revalidate = 0;

interface CachedData {
  timestamp: number;
  models: CamModel[];
}

let cachedModels: CachedData | null = null;
const CACHE_TTL_MS = 20 * 1000; // 20 secondes de cache en mémoire

const COUNTRY_NAMES: Record<string, string> = {
  fr: "France",
  be: "Belgique",
  ch: "Suisse",
  ca: "Canada",
  us: "États-Unis",
  es: "Espagne",
  it: "Italie",
  de: "Allemagne",
  ru: "Russie",
  co: "Colombie",
  br: "Brésil",
  jp: "Japon",
  cn: "Chine",
  kr: "Corée du Sud",
  ua: "Ukraine",
  ro: "Roumanie",
  mx: "Mexique",
  ar: "Argentine",
  gb: "Royaume-Uni",
  nl: "Pays-Bas",
  pl: "Pologne",
  cz: "Tchéquie",
  hu: "Hongrie",
  ve: "Venezuela",
  pe: "Pérou",
  ph: "Philippines",
  th: "Thaïlande"
};

function getCountryFlag(iso?: string | null): string {
  if (!iso || typeof iso !== "string" || iso.length !== 2) return "🌐";
  const code = iso.toUpperCase();
  const first = 0x1F1E6 + code.charCodeAt(0) - 65;
  const second = 0x1F1E6 + code.charCodeAt(1) - 65;
  if (first >= 0x1F1E6 && first <= 0x1F1FF && second >= 0x1F1E6 && second <= 0x1F1FF) {
    return String.fromCodePoint(first, second);
  }
  return "🌐";
}

function getCountryName(iso?: string | null): string {
  if (!iso || typeof iso !== "string") return "International";
  const lower = iso.toLowerCase();
  return COUNTRY_NAMES[lower] || iso.toUpperCase();
}

const DEFAULT_GOALS = [
  "Show Privé 1-to-1",
  "Vibreur Lovense 100%",
  "Strip Intégral & Huile",
  "Gros Plan Cambre",
  "Orgasme en Direct",
  "Show Lingerie & Huile",
  "Danse Sensuelle & Fessée",
  "Dildo Play & Squirt"
];

export async function GET() {
  const now = Date.now();

  // 1. Retour du cache mémoire si valide
  if (cachedModels && (now - cachedModels.timestamp < CACHE_TTL_MS)) {
    return NextResponse.json({
      success: true,
      cached: true,
      count: cachedModels.models.length,
      models: cachedModels.models
    }, {
      headers: {
        "Cache-Control": "public, s-maxage=15, stale-while-revalidate=30"
      }
    });
  }

  try {
    const controller = new AbortController();
    const timeout = setTimeout(() => controller.abort(), 6000);

    const response = await fetch("https://go.stripchat.com/api/models?limit=100", {
      headers: {
        "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/128.0.0.0 Safari/537.36",
        "Accept": "application/json"
      },
      signal: controller.signal
    });

    clearTimeout(timeout);

    if (!response.ok) {
      throw new Error(`Stripchat API HTTP ${response.status}`);
    }

    const data = await response.json();
    const rawList: any[] = Array.isArray(data?.models) ? data.models : [];

    if (rawList.length === 0) {
      throw new Error("Stripchat returned 0 models");
    }

    const mappedModels: CamModel[] = rawList.map((m, idx) => {
      const iso = (typeof m.modelsCountry === "string" ? m.modelsCountry : "").toLowerCase();
      const country = getCountryName(iso);
      const flag = getCountryFlag(iso);
      const langs = Array.isArray(m.languages) ? m.languages : [];
      const isFrench = iso === "fr" || langs.includes("fr");

      let gender: "female" | "couple" | "trans" = "female";
      if (m.gender === "maleFemale" || m.gender === "couple") {
        gender = "couple";
      } else if (m.gender === "trans") {
        gender = "trans";
      }

      let category: "french" | "women" | "couples" | "trans" | "teen" | "milf" | "vr" = "women";
      if (isFrench) {
        category = "french";
      } else if (gender === "couple") {
        category = "couples";
      } else if (gender === "trans") {
        category = "trans";
      } else if (m.broadcastVR) {
        category = "vr";
      } else if (m.isNew) {
        category = "teen";
      } else {
        category = "women";
      }

      const streamUrl = m.stream?.url || m.stream?.urls?.["480p"] || m.stream?.urls?.["original"] || "";
      const viewers = Number(m.viewersCount) || 120 + ((idx * 37) % 800);
      const goalTitle = DEFAULT_GOALS[idx % DEFAULT_GOALS.length];
      const tokensGoal = 500 + ((idx * 150) % 1000);
      const tokensCurrent = Math.floor(tokensGoal * (0.6 + ((idx % 35) / 100)));

      const tags: string[] = [];
      if (isFrench) tags.push("Française");
      tags.push(gender === "couple" ? "Couple" : gender === "trans" ? "Trans" : "Femme");
      if (m.broadcastHD) tags.push("HD");
      tags.push("Lovense");
      if (country && country !== "International") tags.push(country);

      return {
        id: String(m.id || m.username || idx),
        username: String(m.username || `Model_${idx}`),
        age: Number(m.age) || 20 + (idx % 12),
        country,
        flag,
        gender,
        category,
        avatar: m.avatarUrl || m.snapshotUrl || "https://images.unsplash.com/photo-1534528741775-53994a69daeb?w=150&auto=format&fit=crop&q=80",
        snapshot: m.snapshotUrl || m.avatarUrl || "https://images.unsplash.com/photo-1524504388940-b1c1722653e1?w=600&auto=format&fit=crop&q=80",
        streamVideo: streamUrl,
        previewVideo: m.previewUrl || "",
        viewers,
        topic: m.topic || (isFrench ? "Coucou ! En direct • Viens me parler en privé ❤️" : "Live HD Stream • Tip for Lovense & Private Show ❤️"),
        goalTitle,
        tokensGoal,
        tokensCurrent,
        toyConnected: true,
        toyName: "Lovense Lush 3",
        isHd: Boolean(m.broadcastHD ?? true),
        isNew: Boolean(m.isNew),
        tags,
        affiliateUrl: getModelAffiliateUrl(m.username)
      };
    });

    // Mémoriser dans le cache
    cachedModels = {
      timestamp: now,
      models: mappedModels
    };

    return NextResponse.json({
      success: true,
      cached: false,
      count: mappedModels.length,
      models: mappedModels
    }, {
      headers: {
        "Cache-Control": "public, s-maxage=15, stale-while-revalidate=30"
      }
    });

  } catch (err: any) {
    console.error("[CAM_API_ERROR]", err?.message || err);

    // Fallback gracieux sur CAM_MODELS avec affiliation garantie
    const fallbackList = CAM_MODELS.map(m => ({
      ...m,
      affiliateUrl: getModelAffiliateUrl(m.username)
    }));

    return NextResponse.json({
      success: true,
      fallback: true,
      count: fallbackList.length,
      models: fallbackList
    });
  }
}
