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

interface LogEntry {
  type: "feed" | "diaper" | "sleep";
  childId: string;
  subType: string;
  amountMl?: number;
  notes?: string;
  startedAt?: string;
  endedAt?: string;
  loggedAt?: 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: LogEntry = await request.json();
    const { type, childId, subType, amountMl, notes, startedAt, endedAt, loggedAt } = body;

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

    // Use client-provided timestamp (supports time presets) or fall back to now
    const timestamp = loggedAt ? new Date(loggedAt).toISOString() : new Date().toISOString();

    if (type === "feed") {
      const method = subType.includes("breast") ? "breast_both" : "bottle";
      await sql.unsafe(
        `INSERT INTO feeds (child_id, type, method, amount_ml, notes, logged_at) VALUES ($1, $2, $3, $4, $5, $6)`,
        [childId, subType, method, amountMl || null, notes || null, timestamp]
      );
    } else if (type === "diaper") {
      await sql.unsafe(
        `INSERT INTO diapers_logs (child_id, type, notes, logged_at) VALUES ($1, $2, $3, $4)`,
        [childId, subType, notes || null, timestamp]
      );
    } else if (type === "sleep") {
      const startTime = startedAt || timestamp;
      const endTime = endedAt || null;
      const durationMinutes = endTime
        ? Math.round((new Date(endTime).getTime() - new Date(startTime).getTime()) / 60000)
        : null;

      await sql.unsafe(
        `INSERT INTO sleeps (child_id, type, started_at, ended_at, duration_minutes, notes, logged_at) VALUES ($1, $2, $3, $4, $5, $6, $7)`,
        [childId, subType, startTime, endTime, durationMinutes, notes || null, timestamp]
      );
    }

    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");
  const type = searchParams.get("type");
  const limit = parseInt(searchParams.get("limit") || "20");

  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 {
    // No type → return all log types merged, camelCase (used by activity page)
    if (!type) {
      const [feeds, diapers, sleeps] = await Promise.all([
        sql.unsafe(`SELECT id, type as sub_type, amount_ml, notes, logged_at FROM feeds WHERE child_id = $1 ORDER BY logged_at DESC LIMIT $2`, [childId, limit]),
        sql.unsafe(`SELECT id, type as sub_type, notes, logged_at FROM diapers_logs WHERE child_id = $1 ORDER BY logged_at DESC LIMIT $2`, [childId, limit]),
        sql.unsafe(`SELECT id, type as sub_type, notes, logged_at FROM sleeps WHERE child_id = $1 ORDER BY logged_at DESC LIMIT $2`, [childId, limit]),
      ]);

      const all = [
        ...(feeds as any[]).map(r => ({ id: r.id, type: "feed",   subType: r.sub_type, amount: r.amount_ml ?? null, notes: r.notes, loggedAt: r.logged_at })),
        ...(diapers as any[]).map(r => ({ id: r.id, type: "diaper", subType: r.sub_type, amount: null,             notes: r.notes, loggedAt: r.logged_at })),
        ...(sleeps as any[]).map(r => ({ id: r.id, type: "sleep",  subType: r.sub_type, amount: null,             notes: r.notes, loggedAt: r.logged_at })),
      ]
        .sort((a, b) => new Date(b.loggedAt).getTime() - new Date(a.loggedAt).getTime())
        .slice(0, limit);

      return NextResponse.json({ entries: all });
    }

    // Type-specific queries — return raw snake_case rows (used by homepage)
    let results: any[] = [];
    if (type === "feed") {
      results = await sql.unsafe(
        `SELECT * FROM feeds WHERE child_id = $1 ORDER BY logged_at DESC LIMIT $2`,
        [childId, limit]
      );
    } else if (type === "diaper") {
      results = await sql.unsafe(
        `SELECT * FROM diapers_logs WHERE child_id = $1 ORDER BY logged_at DESC LIMIT $2`,
        [childId, limit]
      );
    } else if (type === "sleep") {
      results = await sql.unsafe(
        `SELECT * FROM sleeps WHERE child_id = $1 ORDER BY logged_at DESC LIMIT $2`,
        [childId, limit]
      );
    }

    return NextResponse.json({ entries: results || [] });
  } catch (error) {
    console.error(error);
    return NextResponse.json({ error: String(error) }, { status: 500 });
  }
}