import { NextRequest, NextResponse } from "next/server";
import { upsertEvent, getEventsForDate } from "@/lib/chronicle-db";
import type { ChronicleEvent } from "@/lib/chronicle-db";
import { randomUUID } from "crypto";

export async function GET(request: NextRequest) {
  try {
    const { searchParams } = new URL(request.url);
    const date = searchParams.get("date");
    if (!date) {
      return NextResponse.json({ error: "Missing date parameter" }, { status: 400 });
    }
    const events = getEventsForDate(date);
    return NextResponse.json({ events });
  } catch (err) {
    console.error("[chronicle/events GET]", err);
    return NextResponse.json({ error: "Failed to fetch events" }, { status: 500 });
  }
}

export async function POST(request: NextRequest) {
  try {
    const body = await request.json() as Partial<ChronicleEvent>;

    if (!body.source || !body.type || !body.title) {
      return NextResponse.json(
        { error: "Missing required fields: source, type, title" },
        { status: 400 }
      );
    }

    const now = Date.now();
    const timestamp = body.timestamp ?? now;
    const date = body.date ?? new Date(timestamp).toISOString().slice(0, 10);

    const event: ChronicleEvent = {
      id: body.id ?? randomUUID(),
      date,
      timestamp,
      source: body.source,
      type: body.type,
      title: body.title,
      body: body.body,
      metadata: body.metadata,
    };

    upsertEvent(event);
    return NextResponse.json({ event }, { status: 201 });
  } catch (err) {
    console.error("[chronicle/events POST]", err);
    return NextResponse.json({ error: "Failed to save event" }, { status: 500 });
  }
}
