import { NextResponse } from "next/server";
import { createClient } from "@supabase/supabase-js";

export const runtime = "nodejs";
export const revalidate = 300; // 5 min cache

interface Row {
  id: string;
  slug: string;
  name: string;
  short_name: string | null;
  start_date: string;
  end_date: string;
  venue: string | null;
  city: string | null;
  country: string | null;
  url: string | null;
  status: string;
  hashtag: string | null;
}

export async function GET() {
  const url = process.env.NEXT_PUBLIC_SUPABASE_URL || "";
  const key = process.env.NEXT_PUBLIC_SUPABASE_ANON_KEY || "";
  const schema = process.env.NEXT_PUBLIC_SUPABASE_SCHEMA || "av";
  if (!url || !key) return NextResponse.json({ events: [] }, { status: 200 });

  const sb = createClient(url, key, {
    db: { schema: schema as "public" },
    auth: { persistSession: false },
  });

  const nowIso = new Date().toISOString().slice(0, 10);
  const { data, error } = await sb
    .from("events")
    .select("id,slug,name,short_name,start_date,end_date,venue,city,country,url,status,hashtag")
    .gte("end_date", nowIso)
    .in("status", ["confirmed", "tentative"])
    .order("start_date", { ascending: true })
    .limit(6);

  if (error) return NextResponse.json({ events: [], error: error.message }, { status: 500 });

  const now = new Date();
  const today = new Date(Date.UTC(now.getUTCFullYear(), now.getUTCMonth(), now.getUTCDate()));

  const events = (data || []).map((r: any) => {
    const start = new Date(r.start_date);
    const end = new Date(r.end_date);
    const isLive = today >= start && today <= end;
    const msDay = 86400 * 1000;
    const daysUntil = Math.ceil((start.getTime() - today.getTime()) / msDay);
    const totalDays = Math.max(1, Math.round((end.getTime() - start.getTime()) / msDay) + 1);
    const dayOfEvent = isLive
      ? Math.round((today.getTime() - start.getTime()) / msDay) + 1
      : null;
    return {
      ...r,
      is_live: isLive,
      days_until: daysUntil,
      day_of_event: dayOfEvent,
      total_days: totalDays,
    };
  });

  return NextResponse.json({ events, generated_at: new Date().toISOString() });
}
