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

export async function GET() {
  const guard = await requireAdmin()();
  if ("response" in guard) return guard.response;
  const { session } = guard;

  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(req: NextRequest) {
  const guard = await requireAdminPost()(req);
  if ("response" in guard) return guard.response;
  const { session } = guard;

  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 });
}
