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

// GET /api/medicines/[id]/doses — fetch dose history with corrections
export async function GET(req: NextRequest, { params }: { params: Promise<{ id: string }> }) {
  const { id: medicineId } = await params;
  const auth = await requireFamily();
  if (!auth.success) return NextResponse.json({ error: auth.error }, { status: auth.status });

  const familyId = auth.session!.familyId!;

  // Verify medicine belongs to this family (via child)
  const med = await sql.unsafe(
    `SELECT m.id FROM medicines m JOIN children c ON c.id = m.child_id WHERE m.id = $1 AND c.family_id = $2 LIMIT 1`,
    [medicineId, familyId]
  );
  if (!med[0]) return NextResponse.json({ error: "Not found" }, { status: 404 });

  const doses = await sql.unsafe(
    `SELECT d.*,
       (SELECT json_agg(c ORDER BY c.created_at DESC) FROM log_corrections c WHERE c.dose_id = d.id) AS corrections
     FROM medication_doses d
     WHERE d.medicine_id = $1 AND d.family_id = $2
     ORDER BY d.administered_at DESC
     LIMIT 50`,
    [medicineId, familyId]
  );

  return NextResponse.json({ doses });
}

// POST /api/medicines/[id]/doses — log a new dose
export async function POST(req: NextRequest, { params }: { params: Promise<{ id: string }> }) {
  const { id: medicineId } = await params;
  const auth = await requireFamily();
  if (!auth.success) return NextResponse.json({ error: auth.error }, { status: auth.status });

  const familyId = auth.session!.familyId!;
  const userId = auth.session!.userId;

  const med = await sql.unsafe(
    `SELECT m.id FROM medicines m JOIN children c ON c.id = m.child_id WHERE m.id = $1 AND c.family_id = $2 LIMIT 1`,
    [medicineId, familyId]
  );
  if (!med[0]) return NextResponse.json({ error: "Not found" }, { status: 404 });

  const { amountGiven, notes, administeredAt } = await req.json();

  const [dose] = await sql.unsafe(
    `INSERT INTO medication_doses (medicine_id, family_id, administered_by, amount_given, notes, administered_at)
     VALUES ($1, $2, $3, $4, $5, $6)
     RETURNING *`,
    [medicineId, familyId, userId, amountGiven || null, notes || null, administeredAt || new Date().toISOString()]
  );

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