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

const TABLE: Record<string, string> = {
  feed:   "feeds",
  sleep:  "sleeps",
  diaper: "diapers_logs",
};

export async function DELETE(
  request: Request,
  { params }: { params: Promise<{ id: string }> }
) {
  const auth = await requireFamily();
  if (!auth.success) {
    return NextResponse.json({ error: auth.error }, { status: auth.status });
  }

  const { searchParams } = new URL(request.url);
  const type = searchParams.get("type");
  if (!type || !TABLE[type]) {
    return NextResponse.json({ error: "Invalid or missing type" }, { status: 400 });
  }

  const table     = TABLE[type];
  const familyId  = auth.session!.familyId!;
  const { id }    = await params;

  try {
    // Verify the log belongs to this family via children.family_id
    const rows = await sql.unsafe(
      `SELECT l.id FROM ${table} l
       JOIN children c ON c.id = l.child_id
       WHERE l.id = $1 AND c.family_id = $2`,
      [id, familyId]
    );
    if (!rows || rows.length === 0) {
      return NextResponse.json({ error: "Not found" }, { status: 404 });
    }

    await sql.unsafe(`DELETE FROM ${table} WHERE id = $1`, [id]);
    return NextResponse.json({ success: true });
  } catch (error) {
    console.error(error);
    return NextResponse.json({ error: String(error) }, { status: 500 });
  }
}

export async function PATCH(
  request: Request,
  { params }: { params: Promise<{ id: string }> }
) {
  const auth = await requireFamily();
  if (!auth.success) {
    return NextResponse.json({ error: auth.error }, { status: auth.status });
  }

  const { searchParams } = new URL(request.url);
  const type = searchParams.get("type");
  if (!type || !TABLE[type]) {
    return NextResponse.json({ error: "Invalid or missing type" }, { status: 400 });
  }

  const table    = TABLE[type];
  const familyId = auth.session!.familyId!;
  const { id }   = await params;

  try {
    // Ownership check
    const rows = await sql.unsafe(
      `SELECT l.id FROM ${table} l
       JOIN children c ON c.id = l.child_id
       WHERE l.id = $1 AND c.family_id = $2`,
      [id, familyId]
    );
    if (!rows || rows.length === 0) {
      return NextResponse.json({ error: "Not found" }, { status: 404 });
    }

    const body = await request.json();
    const { notes, amountMl, subType } = body;

    if (type === "feed") {
      await sql.unsafe(
        `UPDATE feeds SET
           type      = COALESCE($2, type),
           amount_ml = COALESCE($3, amount_ml),
           notes     = COALESCE($4, notes)
         WHERE id = $1`,
        [id, subType ?? null, amountMl ?? null, notes ?? null]
      );
    } else if (type === "diaper") {
      await sql.unsafe(
        `UPDATE diapers_logs SET
           type  = COALESCE($2, type),
           notes = COALESCE($3, notes)
         WHERE id = $1`,
        [id, subType ?? null, notes ?? null]
      );
    } else if (type === "sleep") {
      await sql.unsafe(
        `UPDATE sleeps SET
           type  = COALESCE($2, type),
           notes = COALESCE($3, notes)
         WHERE id = $1`,
        [id, subType ?? null, notes ?? null]
      );
    }

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