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

// GET - list family members
export async function GET(request: Request) {
  const auth = await requireFamily();
  if (!auth.success) return NextResponse.json({ error: auth.error }, { status: auth.status });

  try {
    const members = await sql`
      SELECT fm.id, fm.user_id, fm.role, fm.created_at, u.name, u.email
      FROM family_members fm
      LEFT JOIN users u ON u.id = fm.user_id
      WHERE fm.family_id = ${auth.session!.familyId}
      ORDER BY fm.created_at
    `;

    return NextResponse.json({ members: members || [] });
  } catch (error) {
    console.error("Members error:", error);
    return NextResponse.json({ error: String(error) }, { status: 500 });
  }
}

// DELETE - remove member
export async function DELETE(request: Request) {
  const auth = await requireFamily();
  if (!auth.success) return NextResponse.json({ error: auth.error }, { status: auth.status });

  const { searchParams } = new URL(request.url);
  const memberId = searchParams.get("id");

  if (!memberId) {
    return NextResponse.json({ error: "Member ID required" }, { status: 400 });
  }

  try {
    // Only delete if member belongs to this family
    await sql`DELETE FROM family_members WHERE id = ${memberId} AND family_id = ${auth.session!.familyId}`;
    return NextResponse.json({ success: true });
  } catch (error) {
    console.error(error);
    return NextResponse.json({ error: String(error) }, { status: 500 });
  }
}

// PATCH - update member role
export async function PATCH(request: Request) {
  const auth = await requireFamily();
  if (!auth.success) return NextResponse.json({ error: auth.error }, { status: auth.status });

  try {
    const body = await request.json();
    const { memberId, role } = body;

    if (!memberId) {
      return NextResponse.json({ error: "Member ID required" }, { status: 400 });
    }

    await sql`
      UPDATE family_members SET role = ${role || "caregiver"} WHERE id = ${memberId} AND family_id = ${auth.session!.familyId}
    `;

    return NextResponse.json({ success: true });
  } catch (error) {
    console.error(error);
    return NextResponse.json({ error: String(error) }, { status: 500 });
  }
}