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

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

  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 session = await getAdminSession();
  if (!session || session.role !== "SUPER_ADMIN") {
    return NextResponse.json({ error: "Немате дозвола" }, { status: 403 });
  }

  try {
    const { id } = await params;
    const { password } = await req.json();
    if (!password || password.length < 6) {
      return NextResponse.json({ error: "Лозинката мора да има најмалку 6 карактери" }, { 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 });
  }
}
