import { NextRequest, NextResponse } from "next/server";
import { compare } from "bcryptjs";
import { prisma } from "@/lib/prisma";
import { createAdminSession, cookieOptions } from "@/lib/admin-session";
import { adminLoginLimiter, rateLimitHeaders } from "@/lib/rate-limit";
import { SUPER_ADMIN_USERNAME, SUPER_ADMIN_PASSWORD_HASH } from "@/lib/config";

function clientIp(req: NextRequest): string {
  const fwd = req.headers.get("x-forwarded-for");
  if (fwd) return fwd.split(",")[0].trim();
  return req.headers.get("x-real-ip") || "unknown";
}

export async function POST(req: NextRequest) {
  const ip = clientIp(req);
  const limit = adminLoginLimiter.limit(`admin-login:${ip}`);
  if (!limit.success) {
    return NextResponse.json(
      { error: "Премногу обиди. Обидете се повторно подоцна." },
      { status: 429, headers: rateLimitHeaders(limit) }
    );
  }

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

    if (username === SUPER_ADMIN_USERNAME && SUPER_ADMIN_PASSWORD_HASH) {
      const valid = await compare(password, SUPER_ADMIN_PASSWORD_HASH);
      if (!valid) {
        return NextResponse.json({ error: "Невалидно корисничко име или лозинка" }, { status: 401 });
      }
      const session = await createAdminSession({ username: SUPER_ADMIN_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 });
  }
}
