import { NextResponse } from "next/server";
import { prisma } from "../../../lib/prisma";
import { isAdminSession, requireSession } from "../../../lib/auth-helpers";

export async function GET() {
  const { session } = await requireSession();
  if (!session) {
    return NextResponse.json({ error: "Unauthorized" }, { status: 401 });
  }

  const categories = await prisma.category.findMany({
    orderBy: { name: "asc" }
  });

  return NextResponse.json(categories);
}

export async function POST(request: Request) {
  const { session } = await requireSession();
  if (!session) {
    return NextResponse.json({ error: "Unauthorized" }, { status: 401 });
  }

  if (!isAdminSession(session)) {
    return NextResponse.json({ error: "Forbidden" }, { status: 403 });
  }

  const body = await request.json();
  const { name } = body || {};

  if (!name) {
    return NextResponse.json({ error: "Name erforderlich." }, { status: 400 });
  }

  const existing = await prisma.category.findUnique({ where: { name } });
  if (existing) {
    return NextResponse.json({ error: "Kategorie existiert bereits." }, { status: 409 });
  }

  const category = await prisma.category.create({
    data: { name }
  });

  const views = await prisma.userView.findMany({
    select: { id: true }
  });

  if (views.length > 0) {
    await prisma.userViewCategory.createMany({
      data: views.map((view) => ({
        viewId: view.id,
        categoryId: category.id
      }))
    });
  }

  return NextResponse.json(category, { status: 201 });
}

export async function PATCH(request: Request) {
  const { session } = await requireSession();
  if (!session) {
    return NextResponse.json({ error: "Unauthorized" }, { status: 401 });
  }

  if (!isAdminSession(session)) {
    return NextResponse.json({ error: "Forbidden" }, { status: 403 });
  }

  const body = await request.json();
  const { id, name } = body || {};

  if (!id || !name) {
    return NextResponse.json({ error: "ID und Name erforderlich." }, { status: 400 });
  }

  const trimmed = String(name).trim();
  if (!trimmed) {
    return NextResponse.json({ error: "Name erforderlich." }, { status: 400 });
  }

  const existing = await prisma.category.findUnique({ where: { name: trimmed } });
  if (existing && existing.id !== id) {
    return NextResponse.json({ error: "Kategorie existiert bereits." }, { status: 409 });
  }

  const category = await prisma.category.update({
    where: { id },
    data: { name: trimmed }
  });

  return NextResponse.json(category);
}

export async function DELETE(request: Request) {
  const { session } = await requireSession();
  if (!session) {
    return NextResponse.json({ error: "Unauthorized" }, { status: 401 });
  }

  if (!isAdminSession(session)) {
    return NextResponse.json({ error: "Forbidden" }, { status: 403 });
  }

  const { searchParams } = new URL(request.url);
  const id = searchParams.get("id");

  if (!id) {
    return NextResponse.json({ error: "ID erforderlich." }, { status: 400 });
  }

  await prisma.event.updateMany({
    where: { categoryId: id },
    data: { categoryId: null }
  });

  await prisma.category.delete({ where: { id } });

  return NextResponse.json({ ok: true });
}
