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

export async function POST(request: Request) {
  try {
    const { username, password } = await request.json()
    
    console.log('Login attempt for:', username);
    
    // Find user by username, email, or employee ID
    const user = await prisma.user.findFirst({
      where: {
        OR: [
          { username },
          { email: username },
          { employeeId: username }
        ],
        isActive: true
      }
    })
    
    if (!user) {
      return NextResponse.json(
        { error: 'Invalid credentials' },
        { status: 401 }
      )
    }
    
    console.log('User found:', { email: user.email, status: user.status, hasPassword: !!user.passwordHash });
    
    // ========== NEW USERS: Need activation ==========
    if (user.status === 'PENDING_ACTIVATION') {
      // Check if this is a new user (no password set) or existing user awaiting activation
      if (!user.passwordHash || user.passwordHash === '') {
        return NextResponse.json(
          { 
            error: 'Account not activated',
            requiresActivation: true,
            message: 'Please activate your account using the link sent to your email.'
          },
          { status: 403 }
        )
      } else {
        // Existing user who was in PENDING state but has password - treat as ACTIVE
        // This handles edge cases
        await prisma.user.update({
          where: { id: user.id },
          data: { status: 'ACTIVE' }
        });
        // Continue to password verification
      }
    }
    
    // ========== ACTIVE USERS: Normal login ==========
    if (user.status === 'ACTIVE') {
      // Check if password exists
      if (!user.passwordHash || user.passwordHash === '') {
        return NextResponse.json(
          { error: 'Account not fully activated. Please use activation link.' },
          { status: 403 }
        )
      }
      
      // Verify password
      const isValid = await bcrypt.compare(password, user.passwordHash)
      console.log('Password valid:', isValid);
      
      if (!isValid) {
        return NextResponse.json(
          { error: 'Invalid credentials' },
          { status: 401 }
        )
      }
      
      // Update last login
      await prisma.user.update({
        where: { id: user.id },
        data: { lastLoginAt: new Date() }
      })
      
      // Generate JWT token
      const token = jwt.sign(
        { userId: user.id, role: user.role, status: user.status },
        process.env.JWT_SECRET || 'uwezo-hrms-super-secret-key-2026',
        { expiresIn: '7d' }
      )
      
      const response = NextResponse.json({
        success: true,
        user: {
          id: user.id,
          username: user.username,
          email: user.email,
          name: user.name,
          role: user.role,
          dept: user.dept,
          position: user.position,
          isActive: user.isActive,
          isFirstLogin: user.isFirstLogin,
          isIntern: user.isIntern,
          employeeId: user.employeeId,
          status: user.status,
        },
        requiresPasswordChange: user.isFirstLogin
      })
      
      response.cookies.set('auth-token', token, {
        httpOnly: true,
        secure: process.env.NODE_ENV === 'production',
        sameSite: 'lax',
        maxAge: 60 * 60 * 24 * 7,
        path: '/'
      })
      
      return response
    }
    
    // ========== SUSPENDED/INACTIVE USERS ==========
    return NextResponse.json(
      { error: 'Account is not active. Please contact HR.' },
      { status: 403 }
    )
    
  } catch (error) {
    console.error('Login error:', error)
    return NextResponse.json(
      { error: 'Internal server error' },
      { status: 500 }
    )
  }
}
