import { NextResponse } from "next/server";
import { sql } from "@/db";
import { requireFamily } from "@/lib/auth";
import { cookies } from "next/headers";

// POST - create a new family (for onboarding)
export async function POST(request: Request) {
  // This needs authentication but not family yet
  const sessionToken = (await cookies()).get("tia_session")?.value;

  if (!sessionToken) {
    return NextResponse.json({ error: "Not authenticated" }, { status: 401 });
  }

  try {
    const body = await request.json();
    const { name } = body;

    const [family] = await sql.unsafe(
      `INSERT INTO families (name) VALUES ($1) RETURNING *`,
      [name || "My Family"]
    );

    return NextResponse.json({ success: true, family });
  } catch (error) {
    console.error(error);
    return NextResponse.json({ error: String(error) }, { status: 500 });
  }
}

// GET - list families for current user
export async function GET(request: Request) {
  const auth = await requireFamily();
  if (!auth.success) return NextResponse.json({ error: auth.error }, { status: auth.status });

  try {
    const families = await sql.unsafe(
      `SELECT f.* FROM families f
       JOIN family_members fm ON f.id = fm.family_id
       WHERE fm.user_id = $1`,
      [auth.session!.userId]
    );

    return NextResponse.json({ families });
  } catch (error) {
    console.error(error);
    return NextResponse.json({ error: String(error) }, { status: 500 });
  }
}