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

// POST /api/medicines/[id]/doses/[doseId]/correct — create correction record (original is untouched)
export async function POST(req: NextRequest, { params }: { params: Promise<{ id: string; doseId: string }> }) {
  const { id: medicineId, doseId } = 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 dose = await sql.unsafe(
    `SELECT * FROM medication_doses WHERE id = $1 AND family_id = $2 AND medicine_id = $3 LIMIT 1`,
    [doseId, familyId, medicineId]
  );
  if (!dose[0]) return NextResponse.json({ error: "Dose not found" }, { status: 404 });

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

  const originalValue = {
    amountGiven: dose[0].amount_given,
    notes: dose[0].notes,
    administeredAt: dose[0].administered_at,
  };

  const correctedValue = {
    amountGiven: amountGiven ?? dose[0].amount_given,
    notes: notes ?? dose[0].notes,
    administeredAt: administeredAt ?? dose[0].administered_at,
  };

  const [correction] = await sql.unsafe(
    `INSERT INTO log_corrections (family_id, dose_id, original_value, corrected_value, reason, corrected_by)
     VALUES ($1, $2, $3, $4, $5, $6)
     RETURNING *`,
    [familyId, doseId, JSON.stringify(originalValue), JSON.stringify(correctedValue), reason || null, userId]
  );

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