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

export async function GET() {
  const session = await getAdminSession();
  if (!session || session.role !== "SUPER_ADMIN") {
    return NextResponse.json({ error: "Немате дозвола" }, { status: 403 });
  }

  const users = await prisma.adminUser.findMany({
    orderBy: { createdAt: "desc" },
  });

  return NextResponse.json(users);
}

export async function POST(req: NextRequest) {
  const session = await getAdminSession();
  if (!session || session.role !== "SUPER_ADMIN") {
    return NextResponse.json({ error: "Немате дозвола" }, { status: 403 });
  }

  try {
    const { username, password } = await req.json();
    if (!username || !password) {
      return NextResponse.json({ error: "Корисничко име и лозинка се задолжителни" }, { status: 400 });
    }
    if (password.length < 6) {
      return NextResponse.json({ error: "Лозинката мора да има најмалку 6 карактери" }, { status: 400 });
    }

    const existing = await prisma.adminUser.findUnique({ where: { username } });
    if (existing) {
      return NextResponse.json({ error: "Корисничкото име веќе постои" }, { status: 409 });
    }

    const passwordHash = await hash(password, 12);
    const user = await prisma.adminUser.create({
      data: { username, passwordHash, role: "ADMIN" },
    });

    return NextResponse.json(user, { status: 201 });
  } catch (error) {
    console.error("Create admin error:", error);
    return NextResponse.json({ error: "Внатрешна грешка на серверот" }, { status: 500 });
  }
}
