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

export async function GET() {
  const session = await getAdminSession();
  if (!session) {
    return NextResponse.json({ error: "Неавторизирано" }, { status: 401 });
  }

  const where = session.role === "SUPER_ADMIN" ? {} : { createdBy: { username: session.username } };

  const codes = await prisma.code.findMany({
    where,
    orderBy: { createdAt: "desc" },
    include: { createdBy: { select: { username: true } } },
  });

  return NextResponse.json(codes);
}

export async function POST() {
  const session = await getAdminSession();
  if (!session) {
    return NextResponse.json({ error: "Неавторизирано" }, { status: 401 });
  }

  const admin = await prisma.adminUser.findUnique({ where: { username: session.username } });
  if (!admin) {
    return NextResponse.json({ error: "Администраторот не е пронајден" }, { status: 404 });
  }

  const code = randomBytes(6).toString("hex").toUpperCase();

  const created = await prisma.code.create({
    data: {
      code,
      createdById: admin.id,
    },
  });

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