import { NextRequest, NextResponse } from "next/server";
import { hash, compare } from "bcryptjs";
import { prisma } from "@/lib/prisma";
import { requireAdminPost } 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 POST(req: NextRequest) {
  const guard = await requireAdminPost()(req);
  if ("response" in guard) return guard.response;
  const { session } = guard;

  try {
    if (session.username === "super") {
      return NextResponse.json({ error: "SuperAdmin не може да ја промени лозинката преку овој метод" }, { status: 400 });
    }

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

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

    const valid = await compare(currentPassword, admin.passwordHash);
    if (!valid) {
      return NextResponse.json({ error: "Тековната лозинка е неточна" }, { status: 401 });
    }

    const passwordHash = await hash(newPassword, 12);
    await prisma.adminUser.update({
      where: { username: session.username },
      data: { passwordHash },
    });

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