import { NextRequest, NextResponse } from "next/server";
import { hash } from "bcryptjs";
import { prisma } from "@/lib/prisma";
import { 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 DELETE(req: NextRequest, { params }: { params: Promise<{ id: string }> }) {
  const guard = await requireSuperAdminPost()(req);
  if ("response" in guard) return guard.response;

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

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

export async function PUT(req: NextRequest, { params }: { params: Promise<{ id: string }> }) {
  const guard = await requireSuperAdminPost()(req);
  if ("response" in guard) return guard.response;

  try {
    const { id } = await params;
    const { password } = await req.json();
    if (!password || !strongEnough(password)) {
      return NextResponse.json(
        { error: `Лозинката мора да има најмалку ${ADMIN_PASSWORD_MIN_LENGTH} карактери и да содржи буква и цифра` },
        { status: 400 }
      );
    }

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

    const passwordHash = await hash(password, 12);
    await prisma.adminUser.update({
      where: { id },
      data: { passwordHash },
    });

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