import { NextRequest, NextResponse } from 'next/server';
import { getDb } from '@/lib/db';

/**
 * OEFFENTLICHE, ungeschuetzte Stats-Route fuer die Landingpage (yumder.de).
 * Absichtlich NUR unkritische Summen (keine Staedte, keine Sponsoren, keine IDs,
 * keine personenbezogenen Daten). restaurantsCached ist der aktuelle Live-Bestand
 * im OSM-Cache (keine Lifetime-Zaehlung noetig, da die Zahl selbst schon beeindruckend
 * und stets aktuell ist - fuer Social Proof auf der Landingpage).
 *
 * In-Memory-Cache (60s) pro Node-Prozess, damit die Landingpage nicht bei jedem
 * Besuch direkt gegen SQLite laeuft.
 *
 * CORS: Die App laeuft auf app.yumder.de, die Landingpage auf yumder.de - zwei
 * verschiedene Origins (auch "yumder.de" und "app.yumder.de" zaehlen als
 * unterschiedliche Origins, Subdomains sind KEINE Ausnahme). Browser blocken
 * client-seitige fetch()-Aufrufe ueber Origin-Grenzen ohne passende
 * Access-Control-Allow-Origin-Header. Direkte Navigation im Browser ist davon
 * NICHT betroffen, deshalb funktionierte der Link beim manuellen Aufruf, aber
 * nicht beim fetch() von der Landingpage aus.
 */

const ALLOWED_ORIGINS = [
  'https://yumder.de',
  'https://www.yumder.de',
];

let cache: { data: PublicStats; expiresAt: number } | null = null;
const CACHE_TTL_MS = 60_000;

interface PublicStats {
  sessions: number;
  matches: number;
  swipes: number;
  restaurantsCached: number;
}

function ensureCounters(db: ReturnType<typeof getDb>) {
  db.exec(`
    CREATE TABLE IF NOT EXISTS app_counters (
      key   TEXT PRIMARY KEY,
      value INTEGER NOT NULL DEFAULT 0
    );
  `);

  const keys: { key: string; sql: string }[] = [
    { key: 'sessions', sql: 'SELECT COUNT(*) AS c FROM sessions' },
    { key: 'matches', sql: 'SELECT COUNT(*) AS c FROM matches' },
    { key: 'swipes', sql: 'SELECT COUNT(*) AS c FROM swipes' },
  ];

  const upsert = db.prepare(`
    INSERT INTO app_counters(key, value) VALUES (?, ?)
    ON CONFLICT(key) DO NOTHING
  `);

  for (const { key, sql } of keys) {
    const row = db.prepare(sql).get() as { c: number };
    upsert.run(key, row?.c ?? 0);
  }
}

function readCounters(db: ReturnType<typeof getDb>): PublicStats {
  const rows = db.prepare('SELECT key, value FROM app_counters').all() as {
    key: string;
    value: number;
  }[];
  const map: Record<string, number> = {};
  for (const r of rows) map[r.key] = r.value;

  const restaurantsCached = (
    db.prepare('SELECT COUNT(*) AS c FROM restaurants').get() as { c: number }
  ).c;

  return {
    sessions: map.sessions ?? 0,
    matches: map.matches ?? 0,
    swipes: map.swipes ?? 0,
    restaurantsCached,
  };
}

function corsHeaders(req: NextRequest): Record<string, string> {
  const origin = req.headers.get('origin');
  if (origin && ALLOWED_ORIGINS.includes(origin)) {
    return {
      'Access-Control-Allow-Origin': origin,
      'Vary': 'Origin',
    };
  }
  return {};
}

export async function OPTIONS(req: NextRequest) {
  return new NextResponse(null, {
    status: 204,
    headers: {
      ...corsHeaders(req),
      'Access-Control-Allow-Methods': 'GET, OPTIONS',
      'Access-Control-Allow-Headers': 'Content-Type',
    },
  });
}

export async function GET(req: NextRequest) {
  const now = Date.now();
  const extraHeaders = corsHeaders(req);

  if (cache && cache.expiresAt > now) {
    return NextResponse.json(cache.data, {
      headers: { 'Cache-Control': 'public, max-age=30, s-maxage=60', ...extraHeaders },
    });
  }

  const db = getDb();
  ensureCounters(db);
  const data = readCounters(db);

  cache = { data, expiresAt: now + CACHE_TTL_MS };

  return NextResponse.json(data, {
    headers: { 'Cache-Control': 'public, max-age=30, s-maxage=60', ...extraHeaders },
  });
}
