import { NextResponse } from "next/server";

/**
 * Live price feed for the homepage ticker.
 * Pulls from CoinGecko (free, no API key, 30 calls/min) for crypto + USD/VND from open exchange rates fallback.
 *
 * Static fallbacks for symbols without a free public source (SJC, VN-INDEX) — these are placeholder
 * until a proper backend integration is built. We mark them as "static" in the response so the UI
 * can decide whether to display them.
 */

interface Quote {
  symbol: string;
  value: string;
  changePct: number;
  source: "live" | "static";
}

export const revalidate = 60;

async function fetchCoinGecko(): Promise<Record<string, { value: number; change: number }>> {
  try {
    const res = await fetch(
      "https://api.coingecko.com/api/v3/simple/price?ids=bitcoin,ethereum,solana&vs_currencies=usd&include_24hr_change=true",
      { next: { revalidate: 60 }, headers: { accept: "application/json" } }
    );
    if (!res.ok) return {};
    const data = (await res.json()) as Record<string, { usd: number; usd_24h_change: number }>;
    return {
      BTC: { value: data.bitcoin?.usd ?? 0, change: data.bitcoin?.usd_24h_change ?? 0 },
      ETH: { value: data.ethereum?.usd ?? 0, change: data.ethereum?.usd_24h_change ?? 0 },
      SOL: { value: data.solana?.usd ?? 0, change: data.solana?.usd_24h_change ?? 0 },
    };
  } catch {
    return {};
  }
}

async function fetchGoldUsd(): Promise<{ value: number; change: number } | null> {
  // Use metals-api or fallback to a free public endpoint. For Phase 2 we leave a placeholder.
  try {
    const res = await fetch("https://api.gold-api.com/price/XAU", {
      next: { revalidate: 300 },
    });
    if (!res.ok) return null;
    const json = (await res.json()) as { price: number; updatedAt?: string };
    return { value: json.price, change: 0 }; // No change data from this endpoint
  } catch {
    return null;
  }
}

async function fetchUsdVnd(): Promise<{ value: number; change: number } | null> {
  try {
    const res = await fetch("https://open.er-api.com/v6/latest/USD", {
      next: { revalidate: 600 },
    });
    if (!res.ok) return null;
    const json = (await res.json()) as { rates?: { VND?: number } };
    if (!json.rates?.VND) return null;
    return { value: json.rates.VND, change: 0 };
  } catch {
    return null;
  }
}

function fmt(n: number, opts?: Intl.NumberFormatOptions): string {
  return new Intl.NumberFormat("en-US", { maximumFractionDigits: 2, ...opts }).format(n);
}

export async function GET() {
  const [cg, gold, usdVnd] = await Promise.all([fetchCoinGecko(), fetchGoldUsd(), fetchUsdVnd()]);

  const quotes: Quote[] = [];

  if (cg.BTC?.value) quotes.push({ symbol: "BTC", value: fmt(cg.BTC.value, { maximumFractionDigits: 0 }), changePct: cg.BTC.change, source: "live" });
  if (cg.ETH?.value) quotes.push({ symbol: "ETH", value: fmt(cg.ETH.value, { maximumFractionDigits: 0 }), changePct: cg.ETH.change, source: "live" });
  if (cg.SOL?.value) quotes.push({ symbol: "SOL", value: fmt(cg.SOL.value, { maximumFractionDigits: 1 }), changePct: cg.SOL.change, source: "live" });
  if (gold?.value) quotes.push({ symbol: "XAU", value: fmt(gold.value, { maximumFractionDigits: 0 }), changePct: gold.change, source: "live" });
  if (usdVnd?.value) quotes.push({ symbol: "USD/VND", value: fmt(usdVnd.value, { maximumFractionDigits: 0 }), changePct: usdVnd.change, source: "live" });

  // No reliable free SJC and VN-INDEX feed — omit rather than show wrong numbers
  // (Phase 3: integrate VietstockFinance or a paid endpoint)

  return NextResponse.json(
    { quotes, fetchedAt: new Date().toISOString() },
    { headers: { "Cache-Control": "public, s-maxage=60, stale-while-revalidate=120" } }
  );
}
