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

// GET — list members + reported posts (admins only see reports)
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: circleId } = await params;

  const [membership] = await sql.unsafe(
    `SELECT role FROM circle_members WHERE circle_id = $1 AND family_id = $2`,
    [circleId, familyId]
  );
  if (!membership) return NextResponse.json({ error: "Not a member" }, { status: 403 });

  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`,
    [circleId]
  );

  // Admins also see pending reports
  let reports: unknown[] = [];
  if (membership.role === "admin") {
    reports = await sql.unsafe(
      `SELECT pr.id, pr.post_id as "postId", pr.reason,
              f.name as "reportedByName", pr.created_at as "createdAt",
              LEFT(p.body, 100) as "postPreview"
       FROM post_reports pr
       JOIN families f ON f.id = pr.reported_by
       JOIN circle_posts p ON p.id = pr.post_id
       WHERE p.circle_id = $1
       ORDER BY pr.created_at DESC`,
      [circleId]
    );
  }

  return NextResponse.json({ members, reports, myRole: membership.role });
}

// DELETE — leave the circle (self)
// Edge case: last admin cannot leave without first promoting another member
export async function DELETE(
  _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: circleId } = await params;

  const [membership] = await sql.unsafe(
    `SELECT role FROM circle_members WHERE circle_id = $1 AND family_id = $2`,
    [circleId, familyId]
  );
  if (!membership) return NextResponse.json({ error: "Not a member" }, { status: 404 });

  // Block last-admin from leaving
  if (membership.role === "admin") {
    const [{ adminCount }] = await sql.unsafe(
      `SELECT COUNT(*)::int as "adminCount" FROM circle_members WHERE circle_id = $1 AND role = 'admin'`,
      [circleId]
    );
    if (adminCount <= 1) {
      return NextResponse.json({
        error: "You are the only admin. Promote another member before leaving.",
      }, { status: 400 });
    }
  }

  await sql.unsafe(
    `DELETE FROM circle_members WHERE circle_id = $1 AND family_id = $2`,
    [circleId, familyId]
  );
  return NextResponse.json({ success: true });
}
