import { NextResponse } from 'next/server';
import { prisma } from '@/lib/prisma';
import bcrypt from 'bcryptjs';
import jwt from 'jsonwebtoken';

const JWT_SECRET = process.env.JWT_SECRET || 'usfloral-secret-key-2024';

export async function POST(request: Request) {
  try {
    const body = await request.json();
    const { username, password } = body;

    if (!username || !password) {
      return NextResponse.json({ error: 'Usuario o correo y contraseña son requeridos' }, { status: 400 });
    }

    const cleanInput = username.trim().toLowerCase();
    const rawInput = username.trim();

    // Find user in database by username or email (case-insensitive)
    const user = await prisma.user.findFirst({
      where: {
        OR: [
          { email: cleanInput },
          { username: cleanInput },
          { username: rawInput },
          { email: rawInput }
        ]
      }
    });

    if (!user) {
      return NextResponse.json({ error: 'Usuario o contraseña incorrectos' }, { status: 401 });
    }

    // Verify password (supports bcrypt hash or direct plain text matching)
    let passwordMatch = user.password === password.trim();
    if (!passwordMatch) {
      try {
        passwordMatch = await bcrypt.compare(password.trim(), user.password);
      } catch {
        passwordMatch = false;
      }
    }

    if (!passwordMatch) {
      return NextResponse.json({ error: 'Usuario o contraseña incorrectos' }, { status: 401 });
    }

    // If password was stored in plain text, securely upgrade it to bcrypt in the background
    if (user.password === password.trim() && !user.password.startsWith('$2b$')) {
      bcrypt.hash(password.trim(), 10)
        .then(hashed => prisma.user.update({ where: { id: user.id }, data: { password: hashed } }))
        .catch(() => {});
    }

    // Determine target redirect based on role
    let redirectUrl = '/dashboard';
    if (user.role === 'FARM') {
      redirectUrl = '/pedidos';
    } else if (user.role === 'COLD_ROOM') {
      redirectUrl = '/cold-room';
    }

    // Create JWT token
    const token = jwt.sign(
      {
        userId: user.id,
        username: user.username,
        email: user.email,
        name: user.name,
        role: user.role,
        farmId: user.farmId,
        farmName: user.farmName
      },
      JWT_SECRET,
      { expiresIn: '8h' }
    );

    // Set cookie and return success
    const response = NextResponse.json({
      success: true,
      user: {
        id: user.id,
        username: user.username,
        email: user.email,
        name: user.name || user.farmName || user.username,
        role: user.role,
        farmId: user.farmId,
        farmName: user.farmName,
        redirectUrl
      }
    });

    response.cookies.set('auth-token', token, {
      httpOnly: true,
      secure: process.env.NODE_ENV === 'production',
      sameSite: 'lax',
      maxAge: 60 * 60 * 8, // 8 hours
      path: '/',
    });

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