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

// GET - list medicines for a child
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 medicines = await sql.unsafe(
      `SELECT id, name, dose, notes, reminder_time as "reminderTime", created_at as "createdAt"
       FROM medicines WHERE child_id = $1 ORDER BY created_at DESC`,
      [childId]
    );
    return NextResponse.json({ medicines: medicines || [] });
  } catch (error) {
    console.error(error);
    return NextResponse.json({ error: String(error) }, { status: 500 });
  }
}

// POST - create medicine
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 = await request.json();
    const { childId, name, dose, notes, reminderTime } = body;

    if (!childId || !name) {
      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 [medicine] = await sql.unsafe(
      `INSERT INTO medicines (child_id, name, dose, notes, reminder_time)
       VALUES ($1, $2, $3, $4, $5)
       RETURNING id, name, dose, notes, reminder_time as "reminderTime"`,
      [childId, name, dose || null, notes || null, reminderTime || null]
    );

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

// DELETE - delete medicine
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 medicine belongs to a child in user's family
    const medicine = await sql.unsafe(
      `SELECT m.id, m.child_id FROM medicines m
       JOIN children c ON c.id = m.child_id
       WHERE m.id = $1`,
      [id]
    );

    if (!medicine || medicine.length === 0) {
      return NextResponse.json({ error: "Medicine not found or access denied" }, { status: 404 });
    }

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