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

// GET — pending circle invites for the current family
export async function GET() {
  try {
    const auth = await requireFamily();
    if (!auth.success) return NextResponse.json({ error: auth.error }, { status: auth.status });

    const familyId = auth.session!.familyId!;

    const invites = await sql.unsafe(
      `SELECT ci.id, ci.token, ci.circle_id as "circleId",
              c.name as "circleName",
              c.id as "circleId",
              f.name as "inviterName",
              (SELECT COUNT(*) FROM circle_members WHERE circle_id = c.id)::int as "memberCount",
              ci.expires_at as "expiresAt"
       FROM circle_invites ci
       JOIN circles c ON c.id = ci.circle_id
       JOIN families f ON f.id = ci.created_by
       WHERE ci.invited_family_id = $1
         AND ci.consumed_at IS NULL
         AND ci.expires_at > now()
       ORDER BY ci.created_at DESC`,
      [familyId]
    );

    return NextResponse.json({ invites });
  } catch (err: unknown) {
    return NextResponse.json({ error: err instanceof Error ? err.message : String(err) }, { status: 500 });
  }
}
