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

export async function POST(req: NextRequest) {
  try {
    const session = await getAdminSession();
    if (!session) {
      return NextResponse.json({ error: "Неавторизирано" }, { status: 401 });
    }
    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 (newPassword.length < 6) {
      return NextResponse.json({ error: "Новата лозинка мора да има најмалку 6 карактери" }, { 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 });
  }
}
