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

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

  try {
    const family = await sql.unsafe(
      `SELECT id, name, tier, max_children, max_members, pediatrician_phone, pediatrician_name FROM families WHERE id = $1`,
      [auth.session!.familyId]
    );

    if (!family || family.length === 0) {
      return NextResponse.json({ error: "Family not found" }, { status: 404 });
    }

    return NextResponse.json({ family: family[0] });
  } catch (error) {
    console.error(error);
    return NextResponse.json({ error: String(error) }, { status: 500 });
  }
}

// PATCH - update family
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 { name, pediatricianPhone, pediatricianName, tier } = body;

    // Only update fields that are explicitly present in the request body.
    // This avoids COALESCE masking clears and undefined params causing errors.
    const setClauses: string[] = [];
    // eslint-disable-next-line @typescript-eslint/no-explicit-any
    const params: any[] = [];

    if (name !== undefined)             { setClauses.push(`name = $${params.push(name)}`); }
    if (pediatricianPhone !== undefined) { setClauses.push(`pediatrician_phone = $${params.push(pediatricianPhone || null)}`); }
    if (pediatricianName !== undefined)  { setClauses.push(`pediatrician_name = $${params.push(pediatricianName || null)}`); }
    if (tier !== undefined)             { setClauses.push(`tier = $${params.push(tier)}`); }

    if (setClauses.length === 0) return NextResponse.json({ success: true });

    setClauses.push("updated_at = NOW()");
    params.push(auth.session!.familyId);

    await sql.unsafe(
      `UPDATE families SET ${setClauses.join(", ")} WHERE id = $${params.length}`,
      params
    );

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