import { NextResponse } from "next/server";
import { AdminAuthService } from "@/services/AdminAuthService";
import { verifyPassword } from "@/lib/password";
import prisma from "@/lib/prisma";

export async function POST(req: Request) {
    try {
        const { email, password } = await req.json();

        const user = await prisma.user.findUnique({
            where: { email },
        });

        if (!user) {
            return NextResponse.json({ error: "Invalid credentials (user not found)" }, { status: 401 });
        }

        if (!["super_admin", "admin", "moderator", "analyst", "support"].includes(user.role)) {
            return NextResponse.json({ error: `Unauthorized role: ${user.role}` }, { status: 401 });
        }

        // Check lockout
        if (user.locked_until && user.locked_until > new Date()) {
            return NextResponse.json({ error: "Account is temporarily locked due to too many failed attempts" }, { status: 403 });
        }

        const isValidPassword = await verifyPassword(password, user.password_hash);

        if (!isValidPassword) {
            // Increment failed attempts
            const newAttempts = user.failed_login_attempts + 1;
            const lockedUntil = newAttempts >= 5 ? new Date(Date.now() + 15 * 60 * 1000) : null; // Lock for 15 mins after 5 attempts

            await prisma.user.update({
                where: { id: user.id },
                data: {
                    failed_login_attempts: newAttempts,
                    locked_until: lockedUntil,
                },
            });

            return NextResponse.json({ error: "Invalid credentials" }, { status: 401 });
        }

        // Reset failed attempts on success
        if (user.failed_login_attempts > 0) {
            await prisma.user.update({
                where: { id: user.id },
                data: { failed_login_attempts: 0, locked_until: null },
            });
        }

        // Capture request details
        const ipAddress = req.headers.get("x-forwarded-for") || "unknown";
        const userAgent = req.headers.get("user-agent") || "unknown";

        // Create session (requires 2FA by default for admins if setup)
        const sessionStatus = user.requires_2fa ? "2fa_required" : "active";

        const session = await AdminAuthService.createSession(user.id, sessionStatus, {
            ipAddress,
            userAgent,
        });

        await AdminAuthService.logAction({
            userId: user.id,
            action: "admin.login_attempt",
            resourceType: "auth",
            ipAddress,
            userAgent,
            details: { status: sessionStatus },
        });

        const response = NextResponse.json({
            success: true,
            requires2FA: sessionStatus === "2fa_required",
        });

        // Set HTTP-only cookie for admin session
        response.cookies.set("adminSessionToken", session.token, {
            httpOnly: true,
            secure: process.env.NODE_ENV === "production",
            sameSite: "strict",
            path: "/",
            maxAge: 2 * 60 * 60, // 2 hours
        });

        return response;
    } catch (error) {
        console.error("Admin Login Error:", error);
        return NextResponse.json({ error: "Internal server error" }, { status: 500 });
    }
}
