import { NextResponse } from "next/server";
import { sql } from "@/db";
import { requireFamily, requireOwnership } from "@/lib/auth";
import { WHO_BOY_WEIGHT, WHO_GIRL_WEIGHT, getAgeInMonthsFromBirth } from "@/lib/growth-standards";

interface GrowthEntry {
  childId: string;
  measuredAt: string;
  weightKg?: number;
  heightCm?: number;
  headCircumferenceCm?: number;
  notes?: string;
}

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

  try {
    const body: GrowthEntry = await request.json();
    const { childId, measuredAt, weightKg, heightCm, headCircumferenceCm, notes } = body;

    if (!childId || !measuredAt) {
      return NextResponse.json({ error: "Missing required fields" }, { status: 400 });
    }

    // Verify child belongs to user's family
    const ownership = await requireOwnership(childId, "children", "Child");
    if (!ownership.success) {
      return NextResponse.json({ error: ownership.error }, { status: ownership.status });
    }

    const measuredAtDate = new Date(measuredAt).toISOString();
    await sql.unsafe(
      `INSERT INTO growth (child_id, measured_at, weight_kg, height_cm, head_circumference_cm, notes)
       VALUES ($1, $2, $3, $4, $5, $6)`,
      [childId, measuredAtDate, weightKg || null, heightCm || null, headCircumferenceCm || null, notes || null]
    );

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

export async function GET(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 childId = searchParams.get("childId");
  const birthDate = searchParams.get("birthDate");
  const sex = searchParams.get("sex") || "male";

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

  // Verify child belongs to user's family
  const ownership = await requireOwnership(childId, "children", "Child");
  if (!ownership.success) {
    return NextResponse.json({ error: ownership.error }, { status: ownership.status });
  }

  try {
    const growth = await sql.unsafe(
      `SELECT * FROM growth WHERE child_id = $1 ORDER BY measured_at DESC`,
      [childId]
    );

    // Get WHO standards for the child's age
    const ageMonths = birthDate ? getAgeInMonthsFromBirth(birthDate) : 12;
    const whoData = sex === "male" ? WHO_BOY_WEIGHT : WHO_GIRL_WEIGHT;
    const whoStandard = whoData.find((d) => d.ageMonths === ageMonths) || whoData[whoData.length - 1];

    return NextResponse.json({
      growth,
      whoStandard: {
        weight: whoStandard.weight,
        height: whoStandard.height,
        headCircumference: whoStandard.headCircumference,
      }
    });
  } catch (error) {
    console.error(error);
    return NextResponse.json({ error: String(error) }, { status: 500 });
  }
}

export async function PUT(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 { id, measuredAt, weightKg, heightCm, headCircumferenceCm, notes } = body;

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

    // Verify the growth record belongs to a child in user's family
    const existing = await sql.unsafe(
      `SELECT g.child_id FROM growth g
       JOIN children c ON g.child_id = c.id
       JOIN family_members fm ON c.family_id = fm.family_id
       WHERE g.id = $1 AND fm.user_id = (SELECT user_id FROM sessions WHERE session_token = $2 LIMIT 1)`,
      [id, request.headers.get("cookie")?.match(/tia_session=([^;]+)/)?.[1]]
    );

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

    const measuredAtStr = measuredAt ? new Date(measuredAt).toISOString() : null;
    await sql.unsafe(
      `UPDATE growth SET measured_at = $1, weight_kg = $2, height_cm = $3, head_circumference_cm = $4, notes = $5 WHERE id = $6`,
      [measuredAtStr, weightKg ?? null, heightCm ?? null, headCircumferenceCm ?? null, notes ?? null, id]
    );

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

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 id = searchParams.get("id");

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

  try {
    // Verify the growth record belongs to a child in user's family
    const sessionToken = request.headers.get("cookie")?.match(/tia_session=([^;]+)/)?.[1] || "";
    const existing = await sql.unsafe(
      `SELECT g.child_id FROM growth g
       JOIN children c ON g.child_id = c.id
       JOIN family_members fm ON c.family_id = fm.family_id
       WHERE g.id = $1 AND fm.user_id = (SELECT user_id FROM sessions WHERE session_token = $2 LIMIT 1)`,
      [id, sessionToken]
    );

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

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