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

// Helper: verify family is a member; returns role or null
async function getMemberRole(circleId: string, familyId: string): Promise<string | null> {
  const rows = await sql.unsafe(
    `SELECT role FROM circle_members WHERE circle_id = $1 AND family_id = $2`,
    [circleId, familyId]
  );
  return rows[0]?.role ?? null;
}

// GET — circle detail + members list
export async function GET(
  _req: Request,
  { params }: { params: Promise<{ id: string }> }
) {
  const auth = await requireFamily();
  if (!auth.success) return NextResponse.json({ error: auth.error }, { status: auth.status });

  const familyId = auth.session!.familyId!;
  const { id } = await params;

  const role = await getMemberRole(id, familyId);
  if (!role) return NextResponse.json({ error: "Not a member of this circle" }, { status: 403 });

  const [circle] = await sql.unsafe(
    `SELECT id, name, created_by as "createdBy", created_at as "createdAt" FROM circles WHERE id = $1`,
    [id]
  );
  if (!circle) return NextResponse.json({ error: "Circle not found" }, { status: 404 });

  const members = await sql.unsafe(
    `SELECT cm.family_id as "familyId", f.name as "familyName", cm.role, cm.joined_at as "joinedAt"
     FROM circle_members cm
     JOIN families f ON f.id = cm.family_id
     WHERE cm.circle_id = $1
     ORDER BY cm.joined_at ASC`,
    [id]
  );

  return NextResponse.json({ circle: { ...circle, role, memberCount: members.length }, members });
}
