import { NextRequest, NextResponse } from "next/server";
import {
  getOpenDayEvents,
  getOpenDayEvent,
  createOpenDayEvent,
  updateOpenDayEvent,
  deleteOpenDayEvent,
} from "@/lib/db";

export async function GET(request: NextRequest) {
  const idStr = request.nextUrl.searchParams.get("id");
  if (idStr) {
    const id = parseInt(idStr, 10);
    if (isNaN(id)) return NextResponse.json({ error: "Invalid id" }, { status: 400 });
    const event = getOpenDayEvent(id);
    if (!event) return NextResponse.json({ error: "Not found" }, { status: 404 });
    return NextResponse.json(event);
  }
  return NextResponse.json(getOpenDayEvents(), {
    headers: { "Cache-Control": "private, max-age=60" },
  });
}

export async function POST(request: NextRequest) {
  try {
    const body = await request.json();
    if (!body.date || typeof body.date !== "string") {
      return NextResponse.json({ error: "date is required" }, { status: 400 });
    }
    // Warn if date is in the past
    const eventDate = new Date(body.date + "T23:59:59");
    if (eventDate < new Date()) {
      return NextResponse.json({ error: "Дата не может быть в прошлом" }, { status: 400 });
    }
    const id = createOpenDayEvent(body);
    return NextResponse.json({ ok: true, id });
  } catch (err) {
    console.error("[admin/open-day] error:", err);
    return NextResponse.json({ error: "Internal error" }, { status: 500 });
  }
}

export async function PUT(request: NextRequest) {
  try {
    const body = await request.json();
    if (!body.id) return NextResponse.json({ error: "id is required" }, { status: 400 });
    const { id, ...data } = body;
    if (data.date) {
      const eventDate = new Date(data.date + "T23:59:59");
      if (eventDate < new Date()) {
        return NextResponse.json({ error: "Дата не может быть в прошлом" }, { status: 400 });
      }
    }
    updateOpenDayEvent(id, data);
    return NextResponse.json({ ok: true });
  } catch (err) {
    console.error("[admin/open-day] error:", err);
    return NextResponse.json({ error: "Internal error" }, { status: 500 });
  }
}

export async function DELETE(request: NextRequest) {
  const idStr = request.nextUrl.searchParams.get("id");
  if (!idStr) return NextResponse.json({ error: "id is required" }, { status: 400 });
  const id = parseInt(idStr, 10);
  if (isNaN(id)) return NextResponse.json({ error: "Invalid id" }, { status: 400 });
  deleteOpenDayEvent(id);
  return NextResponse.json({ ok: true });
}
