import { NextRequest, NextResponse } from "next/server";
import { prisma } from "@/lib/prisma";
import { getAdminSession } from "@/lib/admin-session";

export async function DELETE(req: NextRequest, { params }: { params: Promise<{ id: string }> }) {
  const session = await getAdminSession();
  if (!session) {
    return NextResponse.json({ error: "Неавторизирано" }, { status: 401 });
  }

  const { id } = await params;
  const code = await prisma.code.findUnique({ where: { id } });
  if (!code) {
    return NextResponse.json({ error: "Кодот не е пронајден" }, { status: 404 });
  }
  if (code.usedByUserId) {
    return NextResponse.json({ error: "Не можете да избришете искористен код" }, { status: 400 });
  }

  if (session.role !== "SUPER_ADMIN") {
    const admin = await prisma.adminUser.findUnique({ where: { username: session.username } });
    if (!admin || code.createdById !== admin.id) {
      return NextResponse.json({ error: "Немате дозвола" }, { status: 403 });
    }
  }

  await prisma.code.delete({ where: { id } });
  return NextResponse.json({ success: true });
}
