import { logError } from "@/lib/logger";
import { NextRequest, NextResponse } from "next/server";
import { login, buildSetCookieHeader } from "@/lib/auth";
import { createAuditLog } from "@/lib/log";

export const runtime = "nodejs";

export async function POST(req: NextRequest) {
  try {
    const body = await req.json() as {
      username?: string;
      password?: string;
    };
    const { username = "", password = "" } = body;

    if (!username || !password) {
      return NextResponse.json(
        { error: "用户名和密码不能为空" },
        { status: 400 }
      );
    }

    const result = await login(username, password);
    if (!result) {
      // 记录登录失败
      const ip = req.headers.get("x-forwarded-for") || req.headers.get("x-real-ip") || "unknown";
      const ua = req.headers.get("user-agent") || "unknown";
      await createAuditLog({
        userId: 0,
        username,
        action: "login",
        resource: "auth",
        result: "failure",
        errorMessage: "Invalid credentials",
        ipAddress: ip,
        userAgent: ua,
      });

      return NextResponse.json(
        { error: "用户名或密码错误" },
        { status: 401 }
      );
    }

    // 记录登录成功
    const ip = req.headers.get("x-forwarded-for") || req.headers.get("x-real-ip") || "unknown";
    const ua = req.headers.get("user-agent") || "unknown";
    await createAuditLog({
      userId: result.adminSession.userId,
      username: result.adminSession.username,
      action: "login",
      resource: "auth",
      result: "success",
      ipAddress: ip,
      userAgent: ua,
    });

    const response = NextResponse.json({
      user: {
        id: result.adminSession.userId,
        username: result.adminSession.username,
        roles: result.adminSession.roles,
        permissions: result.adminSession.permissions,
      },
    });

    response.headers.set(
      "Set-Cookie",
      buildSetCookieHeader(result.sessionId)
    );

    return response;
  } catch (e) {
    logError("Login error:", e);
    return NextResponse.json({ error: "服务器错误" }, { status: 500 });
  }
}
