import { NextRequest, NextResponse } from 'next/server';
import { logError } from '@/lib/logger';
import { loginViaService, logAudit } from '@/lib/platform-client';
import { getRequestProductId } from '@/lib/product-config';

export async function POST(req: NextRequest) {
  try {
    const { email, password } = await req.json();
    if (!email || !password) {
      return NextResponse.json({ error: 'Email and password are required' }, { status: 400 });
    }
    const ip = req.headers.get('x-forwarded-for') ?? req.headers.get('x-real-ip') ?? '';
    const userAgent = req.headers.get('user-agent') ?? '';

    try {
      const result = await loginViaService(email, password, getRequestProductId(req));

      await logAudit({
        userId: result.user.id,
        action: 'login_success',
        category: 'auth',
        details: { ip, userAgent, email: result.user.email },
      });

      return NextResponse.json({
        accessToken: result.accessToken,
        refreshToken: result.refreshToken,
        user: {
          id: result.user.id,
          email: result.user.email,
          name: result.user.displayName,
          role: result.user.role,
          plan: result.user.plan,
        },
      });
    } catch {
      await logAudit({
        userId: email,
        action: 'login_failed',
        category: 'auth',
        details: { ip, userAgent },
      });
      return NextResponse.json({ error: 'Invalid credentials' }, { status: 401 });
    }
  } catch (error) {
    logError('Login error', error);
    return NextResponse.json({ error: 'Internal server error' }, { status: 500 });
  }
}
