/**
 * GET  /api/sessions          — list current user's chat sessions
 * POST /api/sessions          — create a new session { title?, context_doc_id?, context_page_id? }
 */
import { NextResponse } from "next/server";
import { createClient, isSupabaseConfigured } from "@/lib/supabase/server";

export async function GET() {
  if (!isSupabaseConfigured()) return NextResponse.json({ sessions: [] });
  const supabase = await createClient();
  const { data: { user } } = await supabase.auth.getUser();
  if (!user) return NextResponse.json({ error: "unauthenticated" }, { status: 401 });

  const { data, error } = await supabase
    .from("chat_sessions")
    .select("id, title, summary, context_doc_id, context_page_id, message_count, total_cost_usd, updated_at, is_public")
    .eq("archived", false)
    .order("updated_at", { ascending: false })
    .limit(50);

  if (error) return NextResponse.json({ error: error.message }, { status: 500 });
  return NextResponse.json({ sessions: data });
}

export async function POST(request: Request) {
  if (!isSupabaseConfigured()) return NextResponse.json({ error: "auth_disabled" }, { status: 503 });
  const supabase = await createClient();
  const { data: { user } } = await supabase.auth.getUser();
  if (!user) return NextResponse.json({ error: "unauthenticated" }, { status: 401 });

  const body = (await request.json().catch(() => ({}))) as {
    title?: string; context_doc_id?: string; context_page_id?: string;
  };

  const { data, error } = await supabase
    .from("chat_sessions")
    .insert({
      user_id: user.id,
      title: body.title ?? null,
      context_doc_id: body.context_doc_id ?? null,
      context_page_id: body.context_page_id ?? null,
    })
    .select("id, title, context_doc_id, context_page_id, created_at")
    .single();

  if (error) return NextResponse.json({ error: error.message }, { status: 500 });
  return NextResponse.json({ session: data });
}
