import { NextResponse } from 'next/server';
import { AUTH_COOKIE_NAME, authCookieSecure, configuredUsername, isAuthConfigured, makeAuthToken, validateCredentials } from '@/lib/auth';
import { recordEvent } from '@/lib/auditDb';

export const runtime = 'nodejs';
export const dynamic = 'force-dynamic';

export async function POST(req: Request) {
  if (!isAuthConfigured()) {
    recordEvent({ action: 'auth.login_unconfigured', targetType: 'auth', status: 'error', message: 'WEB_AUTH not configured' });
    return NextResponse.json({ error: 'WEB_AUTH not configured' }, { status: 503 });
  }

  const body = await req.json().catch(() => ({})) as { username?: unknown; password?: unknown; remember?: unknown };
  const username = String(body.username || '');
  const password = String(body.password || '');
  const remember = body.remember !== false;

  if (!validateCredentials(username, password)) {
    recordEvent({ action: 'auth.login_failed', targetType: 'auth', targetId: username.trim() || null, status: 'error' });
    return NextResponse.json({ error: '用户名或密码不正确' }, { status: 401 });
  }

  const ttlSeconds = remember ? 60 * 60 * 24 * 30 : 60 * 60 * 12;
  const response = NextResponse.json({ ok: true, username: configuredUsername() });
  response.cookies.set({
    name: AUTH_COOKIE_NAME,
    value: makeAuthToken(configuredUsername(), ttlSeconds),
    maxAge: ttlSeconds,
    httpOnly: true,
    secure: authCookieSecure(),
    sameSite: 'lax',
    path: '/',
  });
  recordEvent({ action: 'auth.login_ok', targetType: 'auth', targetId: configuredUsername(), status: 'ok', metadata: { remember } });
  return response;
}
