import { NextRequest, NextResponse } from 'next/server';
import { getPrisma } from '@/lib/db';
import { comparePassword, signJwt } from '@/lib/auth';

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

    if (!username || !password) {
      return NextResponse.json(
        { error: 'El nombre de usuario y la contraseña son obligatorios.' },
        { status: 400 }
      );
    }

    // Run lookup as ADMIN to bypass RLS since the user is not authenticated yet
    const prismaAdmin = getPrisma({
      userId: 0,
      username: 'login_system',
      email: 'system@estelar.com',
      role: 'admin',
      hotelId: 0,
      regionId: 0
    });

    console.log('[Login API] DATABASE_URL in Next.js:', process.env.DATABASE_URL);
    console.log('[Login API] Attempting login for username:', username);
    try {
      const dbRole = await prismaAdmin.$queryRaw`SELECT current_setting('app.current_user_role', true) as role;`;
      console.log('[DEBUG LOGIN] current_setting role inside Next.js:', JSON.stringify(dbRole));
    } catch (e) {
      console.error('[DEBUG LOGIN] Failed to fetch current_setting role:', e);
    }
    const user = await prismaAdmin.user.findUnique({
      where: { username },
      include: { hotel: true }
    });
    console.log('[Login API] User found in DB:', user ? { id: user.id, username: user.username, role: user.role, status: user.status } : null);

    if (!user || user.status !== 'ACTIVE') {
      console.log('[Login API] Login failed: User not found or inactive');
      return NextResponse.json(
        { error: 'Credenciales inválidas o usuario inactivo.' },
        { status: 401 }
      );
    }

    const passwordMatch = await comparePassword(password, user.passwordHash);
    console.log('[Login API] Password match result:', passwordMatch);
    if (!passwordMatch) {
      console.log('[Login API] Login failed: Password mismatch');
      return NextResponse.json(
        { error: 'Credenciales inválidas.' },
        { status: 401 }
      );
    }

    // Create session payload
    const sessionPayload = {
      userId: user.id,
      username: user.username,
      email: user.email,
      role: user.role,
      hotelId: user.hotelId,
      regionId: user.hotel.regionId
    };

    // Sign JWT
    const token = signJwt(sessionPayload);

    // Set cookie
    const response = NextResponse.json({
      user: {
        id: user.id,
        username: user.username,
        email: user.email,
        role: user.role,
        hotelId: user.hotelId,
        area: user.area
      }
    });

    response.cookies.set({
      name: 'session',
      value: token,
      httpOnly: true,
      secure: process.env.NODE_ENV === 'production',
      sameSite: 'lax',
      path: '/',
      maxAge: 86400 // 1 day
    });

    // Record login audit log
    await prismaAdmin.auditLog.create({
      data: {
        userId: user.id,
        action: 'LOGIN',
        targetTable: 'users',
        targetId: user.id,
        ipAddress: req.headers.get('x-forwarded-for') || '127.0.0.1'
      }
    });

    return response;
  } catch (err) {
    console.error('Login error:', err);
    return NextResponse.json(
      { error: 'Error interno del servidor.' },
      { status: 500 }
    );
  }
}
