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

// DELETE — admin removes a member OR promotes/demotes (via PATCH)
export async function DELETE(
  _req: Request,
  { params }: { params: Promise<{ id: string; memberId: 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, memberId: targetFamilyId } = await params;

  // Only admins can remove other members
  const [membership] = await sql.unsafe(
    `SELECT role FROM circle_members WHERE circle_id = $1 AND family_id = $2`,
    [circleId, familyId]
  );
  if (membership?.role !== "admin") {
    return NextResponse.json({ error: "Only circle admins can remove members" }, { status: 403 });
  }

  // Admins cannot remove themselves via this route (use /members DELETE to leave)
  if (targetFamilyId === familyId) {
    return NextResponse.json({ error: "Use the leave action to remove yourself" }, { status: 400 });
  }

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

// PATCH — promote member to admin (admin only)
export async function PATCH(
  req: Request,
  { params }: { params: Promise<{ id: string; memberId: 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, memberId: targetFamilyId } = await params;

  const [membership] = await sql.unsafe(
    `SELECT role FROM circle_members WHERE circle_id = $1 AND family_id = $2`,
    [circleId, familyId]
  );
  if (membership?.role !== "admin") {
    return NextResponse.json({ error: "Only admins can change roles" }, { status: 403 });
  }

  const { role } = await req.json();
  if (!["admin", "member"].includes(role)) {
    return NextResponse.json({ error: "Invalid role" }, { status: 400 });
  }

  await sql.unsafe(
    `UPDATE circle_members SET role = $1 WHERE circle_id = $2 AND family_id = $3`,
    [role, circleId, targetFamilyId]
  );
  return NextResponse.json({ success: true });
}
