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

function strongEnough(password: string): boolean {
  if (password.length < ADMIN_PASSWORD_MIN_LENGTH) return false;
  return /[A-Za-z]/.test(password) && /\d/.test(password);
}

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

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

  return NextResponse.json(users);
}

export async function POST(req: NextRequest) {
  const guard = await requireSuperAdminPost()(req);
  if ("response" in guard) return guard.response;

  try {
    const { username, password } = await req.json();
    if (!username || !password) {
      return NextResponse.json({ error: "Корисничко име и лозинка се задолжителни" }, { status: 400 });
    }
    if (!strongEnough(password)) {
      return NextResponse.json(
        { error: `Лозинката мора да има најмалку ${ADMIN_PASSWORD_MIN_LENGTH} карактери и да содржи буква и цифра` },
        { 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 });
  }
}
