import { NextResponse } from "next/server";
import { prisma } from "@/lib/prisma";
import { verifyPassword } from "@/lib/auth";
import { createSessionToken, getSessionCookieName, getSessionTtlSeconds } from "@/lib/session";
import { isRateLimited, getClientIp } from "@/lib/rate-limit";

// 登录速率限制：每个 IP 60 秒内最多 5 次尝试
const LOGIN_MAX_ATTEMPTS = 5;
const LOGIN_WINDOW_MS = 60 * 1000;

export async function POST(req: Request) {
    const clientIp = getClientIp(req);
    if (isRateLimited(`login:${clientIp}`, LOGIN_MAX_ATTEMPTS, LOGIN_WINDOW_MS)) {
        return NextResponse.json(
            { error: "Too many login attempts, please try again later" },
            { status: 429 }
        );
    }

    try {
        const { password, rememberMe, durationDays } = await req.json().catch(() => ({}));
        if (typeof password !== "string" || password.length === 0) {
            return NextResponse.json({ error: "Invalid password" }, { status: 400 });
        }

        const settings = await prisma.globalSettings.findUnique({
            where: { id: "default" },
        });

        if (!settings) {
            return NextResponse.json({ error: "Settings not initialized" }, { status: 503 });
        }

        const isValid = await verifyPassword(password, settings.password);

        if (isValid) {
            const rawDays = rememberMe ? Number(durationDays) : 1;
            const boundedDays = Number.isFinite(rawDays) ? Math.floor(rawDays) : 1;
            const days = rememberMe ? Math.max(1, Math.min(30, boundedDays)) : 1;
            const token = await createSessionToken(days);
            const response = NextResponse.json({ success: true });
            response.cookies.set(getSessionCookieName(), token, {
                httpOnly: true,
                secure: process.env.NODE_ENV === "production",
                sameSite: "lax",
                path: "/",
                maxAge: getSessionTtlSeconds(days),
            });
            return response;
        } else {
            return NextResponse.json({ error: "Invalid password" }, { status: 401 });
        }
    } catch {
        return NextResponse.json({ error: "Login failed" }, { status: 500 });
    }
}
