import { NextRequest, NextResponse } from "next/server";
import {
  getOpenDayClasses,
  addOpenDayClass,
  updateOpenDayClass,
  deleteOpenDayClass,
} from "@/lib/db";

export async function GET(request: NextRequest) {
  const eventIdStr = request.nextUrl.searchParams.get("eventId");
  if (!eventIdStr) return NextResponse.json({ error: "eventId is required" }, { status: 400 });
  const eventId = parseInt(eventIdStr, 10);
  if (isNaN(eventId)) return NextResponse.json({ error: "Invalid eventId" }, { status: 400 });
  return NextResponse.json(getOpenDayClasses(eventId));
}

export async function POST(request: NextRequest) {
  try {
    const body = await request.json();
    const { eventId, hall, startTime, endTime, trainer, style } = body;
    if (!eventId || !hall || !startTime || !endTime || !trainer || !style) {
      return NextResponse.json({ error: "All fields required" }, { status: 400 });
    }
    const id = addOpenDayClass(eventId, { hall, startTime, endTime, trainer, style });
    return NextResponse.json({ ok: true, id });
  } catch (e) {
    const msg = e instanceof Error ? e.message : "Internal error";
    if (msg.includes("UNIQUE")) {
      return NextResponse.json({ error: "Этот слот уже занят" }, { status: 409 });
    }
    return NextResponse.json({ error: msg }, { 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;
    updateOpenDayClass(id, data);
    return NextResponse.json({ ok: true });
  } catch (err) {
    console.error("[admin/open-day/classes] 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 });
  deleteOpenDayClass(id);
  return NextResponse.json({ ok: true });
}
