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

interface BulkEntry {
  vaccineName: string;
  scheduledDate: string;
  givenDate?: string;
  status: "given" | "unknown" | "pending";
  notes?: string;
}

// POST /api/vaccinations/bulk — onboarding vaccination history setup
export async function POST(request: Request) {
  const auth = await requireFamily();
  if (!auth.success) return NextResponse.json({ error: auth.error }, { status: auth.status });

  const { childId, entries } = await request.json() as { childId: string; entries: BulkEntry[] };

  if (!childId || !Array.isArray(entries)) {
    return NextResponse.json({ error: "childId and entries required" }, { status: 400 });
  }

  const ownership = await requireOwnership(childId, "children", "Child");
  if (!ownership.success) return NextResponse.json({ error: ownership.error }, { status: ownership.status });

  let inserted = 0;
  for (const e of entries) {
    if (!e.vaccineName || !e.scheduledDate) continue;
    const status = e.status === "given" ? "given" : e.status === "unknown" ? "pending" : "pending";
    await sql.unsafe(
      `INSERT INTO vaccinations (child_id, vaccine_name, scheduled_date, given_date, status, notes)
       VALUES ($1, $2, $3, $4, $5, $6)
       ON CONFLICT DO NOTHING`,
      [childId, e.vaccineName, e.scheduledDate, e.givenDate || null, status, e.notes || null]
    );
    inserted++;
  }

  return NextResponse.json({ success: true, inserted });
}
