import { NextResponse } from "next/server";
import { cookies } from "next/headers";
import { verifyPassword } from "@/lib/auth/password";
import { signToken } from "@/lib/auth/jwt";
import { findByUsername, getPasswordHash } from "@/lib/db/repos/usersRepo";
import { checkLock, recordFail, recordSuccess, getClientIp } from "@/lib/auth/loginLimiter";

export async function POST(request) {
  try {
    const ip = getClientIp(request);
    const lock = checkLock(ip);
    if (lock.locked) {
      return NextResponse.json(
        { error: `Too many failed attempts. Try again in ${lock.retryAfter}s.`, retryAfter: lock.retryAfter },
        { status: 429, headers: { "Retry-After": String(lock.retryAfter) } }
      );
    }

    const body = await request.json();
    const { username, password } = body || {};

    if (!username || !password) {
      return NextResponse.json({ error: "Username and password are required" }, { status: 400 });
    }

    const user = await findByUsername(username.trim());

    // Generic error for both missing user and wrong password
    if (!user) {
      recordFail(ip);
      return NextResponse.json({ error: "Invalid credentials" }, { status: 401 });
    }

    if (!user.is_active) {
      return NextResponse.json({ error: "Account disabled" }, { status: 403 });
    }

    if (!user.is_approved) {
      return NextResponse.json({ error: "Account pending approval" }, { status: 403 });
    }

    const passwordHash = await getPasswordHash(username.trim());
    const valid = passwordHash ? verifyPassword(password, passwordHash) : false;
    if (!valid) {
      recordFail(ip);
      return NextResponse.json({ error: "Invalid credentials" }, { status: 401 });
    }

    recordSuccess(ip);
    const token = await signToken({
      userId: user.id,
      username: user.username,
      role: user.role,
    });

    const cookieStore = await cookies();
    cookieStore.set("auth_token", token, {
      httpOnly: true,
      secure: process.env.AUTH_COOKIE_SECURE === "true",
      sameSite: "lax",
      path: "/",
      maxAge: 7 * 24 * 60 * 60, // 7 days
    });

    return NextResponse.json({
      user: {
        id: user.id,
        username: user.username,
        role: user.role,
      },
    }, { status: 200 });
  } catch (error) {
    console.error("[login] error:", error);
    return NextResponse.json({ error: "Login failed" }, { status: 500 });
  }
}
