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

interface VaccinationEntry {
  childId: string;
  vaccineName: string;
  scheduledDate: string;
  givenDate?: string;
  status?: "pending" | "given" | "skipped" | "delayed";
  provider?: string;
  lotNumber?: string;
  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: VaccinationEntry = await request.json();
    const { childId, vaccineName, scheduledDate, givenDate, status, provider, lotNumber, notes } = body;

    if (!childId || !vaccineName || !scheduledDate) {
      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 });
    }

    await sql.unsafe(
      `INSERT INTO vaccinations (child_id, vaccine_name, scheduled_date, given_date, status, provider, lot_number, notes)
       VALUES ($1, $2, $3, $4, $5, $6, $7, $8)`,
      [childId, vaccineName, scheduledDate, givenDate || null, status || "pending", provider || null, lotNumber || 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");

  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 vaccinations = await sql.unsafe(
      `SELECT * FROM vaccinations WHERE child_id = $1 ORDER BY scheduled_date ASC`,
      [childId]
    );

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