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

const SUPER_USERNAME = "super";
const SUPER_PASSWORD = "admin";

export async function POST(req: NextRequest) {
  try {
    const { username, password } = await req.json();
    if (!username || !password) {
      return NextResponse.json({ error: "Корисничко име и лозинка се задолжителни" }, { status: 400 });
    }

    if (username === SUPER_USERNAME && password === SUPER_PASSWORD) {
      const session = await createAdminSession({ username: SUPER_USERNAME, role: "SUPER_ADMIN" });
      const res = NextResponse.json({ success: true });
      res.cookies.set(cookieOptions(session));
      return res;
    }

    const admin = await prisma.adminUser.findUnique({ where: { username } });
    if (!admin) {
      return NextResponse.json({ error: "Невалидно корисничко име или лозинка" }, { status: 401 });
    }

    const valid = await compare(password, admin.passwordHash);
    if (!valid) {
      return NextResponse.json({ error: "Невалидно корисничко име или лозинка" }, { status: 401 });
    }

    const session = await createAdminSession({ username: admin.username, role: admin.role });
    const res = NextResponse.json({ success: true });
    res.cookies.set(cookieOptions(session));
    return res;
  } catch (error) {
    console.error("Admin login error:", error);
    return NextResponse.json({ error: "Внатрешна грешка на серверот" }, { status: 500 });
  }
}
