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

// GET — list all circles this family belongs to
export async function GET() {
  const auth = await requireFamily();
  if (!auth.success) return NextResponse.json({ error: auth.error }, { status: auth.status });

  const familyId = auth.session!.familyId!;

  const circles = await sql.unsafe(
    `SELECT c.id, c.name, c.created_by as "createdBy", c.created_at as "createdAt",
            cm.role,
            (SELECT COUNT(*) FROM circle_members WHERE circle_id = c.id)::int as "memberCount"
     FROM circles c
     JOIN circle_members cm ON cm.circle_id = c.id AND cm.family_id = $1
     ORDER BY c.created_at DESC`,
    [familyId]
  );

  return NextResponse.json({ circles });
}

// POST — create a new circle (creator becomes admin)
export async function POST(request: Request) {
  const auth = await requireFamily();
  if (!auth.success) return NextResponse.json({ error: auth.error }, { status: auth.status });

  const familyId = auth.session!.familyId!;
  const { name } = await request.json();

  if (!name?.trim()) {
    return NextResponse.json({ error: "Circle name is required" }, { status: 400 });
  }

  try {
    const [circle] = await sql.unsafe(
      `INSERT INTO circles (name, created_by) VALUES ($1, $2)
       RETURNING id, name, created_by as "createdBy", created_at as "createdAt"`,
      [name.trim(), familyId]
    );

    await sql.unsafe(
      `INSERT INTO circle_members (circle_id, family_id, role) VALUES ($1, $2, 'admin')`,
      [circle.id, familyId]
    );

    return NextResponse.json({ success: true, circle: { ...circle, role: "admin", memberCount: 1 } });
  } catch (err: unknown) {
    const msg = err instanceof Error ? err.message : String(err);
    return NextResponse.json({ error: msg }, { status: 500 });
  }
}
