﻿import { NextResponse } from 'next/server';
import { requireAuth } from '@/lib/auth-helper';
import { prisma } from '@/lib/prisma';
import bcrypt from 'bcryptjs';
import crypto from 'crypto';
import { sendActivationEmail } from '@/lib/emailservice.cjs';

export async function GET(request: Request) {
  const auth = await requireAuth(['admin', 'hr']);
  if (auth.error) {
    return NextResponse.json({ error: auth.error }, { status: auth.status });
  }

  try {
    const { searchParams } = new URL(request.url);
    const department = searchParams.get('department');
    const search = searchParams.get('search');

    const where: any = {};
    if (department && department !== 'All') where.dept = department;
    if (search) {
      where.OR = [
        { fullName: { contains: search } },
        { email: { contains: search } },
        { employeeNumber: { contains: search } }
      ];
    }

    const employees = await prisma.employee.findMany({
      where,
      orderBy: { fullName: 'asc' }
    });

    return NextResponse.json(employees);
  } catch (error) {
    console.error('Error fetching employees:', error);
    return NextResponse.json({ error: 'Internal Server Error' }, { status: 500 });
  }
}

export async function POST(request: Request) {
  const auth = await requireAuth(['admin', 'hr']);
  if (auth.error) {
    return NextResponse.json({ error: auth.error }, { status: auth.status });
  }

  try {
    const body = await request.json();
    
    // Map HR frontend fields
    const fullName = body.name || body.fullName;
    const email = body.email;
    const phone = body.phone;
    const gender = body.gender || 'Male';
    const dept = body.department || body.dept;
    const position = body.position;
    const joinDate = body.startDate || body.joinDate;
    const salary = body.salary;
    const employmentType = body.isIntern ? 'Intern' : (body.employmentType || 'Permanent');
    const dob = body.dob;
    const nationalId = body.nationalId;
    const kraPin = body.kraPin;
    const employeeId = body.employeeId;
    
    console.log('HR Portal - Creating employee for email:', email, 'Department:', dept);
    
    // Validate required fields
    const missingFields = [];
    if (!fullName) missingFields.push('fullName');
    if (!email) missingFields.push('email');
    if (!dept) missingFields.push('dept');
    if (!position) missingFields.push('position');
    if (!joinDate) missingFields.push('joinDate');
    
    if (missingFields.length > 0) {
      return NextResponse.json(
        { error: `Missing required fields: ${missingFields.join(', ')}` },
        { status: 400 }
      );
    }
    
    // Check for duplicate email in User table
    const existingUser = await prisma.user.findFirst({
      where: { email }
    });

    if (existingUser) {
      return NextResponse.json(
        { error: `Email "${email}" is already registered in the system.` },
        { status: 409 }
      );
    }

    // Check for duplicate email in Employee table
    const existingEmployee = await prisma.employee.findFirst({
      where: { email }
    });

    if (existingEmployee) {
      return NextResponse.json(
        { error: `Email "${email}" is already registered as an employee.` },
        { status: 409 }
      );
    }
    
    const isIntern = employmentType === 'Intern';
    const prefix = isIntern ? 'INT' : 'UF';
    
    // Generate next employee number if not provided
    let empNumber = employeeId;
    if (!empNumber) {
      const lastEmployee = await prisma.employee.findFirst({
        where: { employeeNumber: { startsWith: prefix } },
        orderBy: { employeeNumber: 'desc' }
      });
      
      let nextNum = 1;
      if (lastEmployee) {
        const num = parseInt(lastEmployee.employeeNumber.replace(prefix, ''));
        if (!isNaN(num)) {
          nextNum = num + 1;
        }
      }
      empNumber = `${prefix}${nextNum.toString().padStart(3, '0')}`;
    }
    
    const username = empNumber.toLowerCase();
    const tempPassword = `${username}@${new Date().getFullYear()}`;
    const hashedPassword = await bcrypt.hash(tempPassword, 10);
    const salaryNum = salary ? parseFloat(salary) : null;
    
    // Split full name
    const nameParts = fullName.trim().split(' ');
    const firstName = nameParts[0];
    const lastName = nameParts.slice(1).join(' ') || '';
    
    // Create employee
    const employee = await prisma.employee.create({
      data: {
        employeeNumber: empNumber,
        firstName,
        lastName,
        fullName,
        email,
        phone: phone || null,
        dob: dob ? new Date(dob) : null,
        gender: gender || 'Male',
        employmentType: employmentType || 'Permanent',
        dept,
        position,
        joinDate: new Date(joinDate),
        salary: salaryNum,
        nationalId: nationalId || null,
        kraPin: kraPin || null,
        isIntern,
        isActive: true,
      },
    });
    
    console.log('✅ Employee created:', employee.email);
    
    // Generate activation token
    const activationToken = crypto.randomBytes(32).toString('hex');
    const tokenExpiry = new Date();
    tokenExpiry.setHours(tokenExpiry.getHours() + 24);
    
    // Create user account
    const user = await prisma.user.create({
      data: {
        username,
        passwordHash: hashedPassword,
        email,
        name: fullName,
        role: isIntern ? 'intern' : 'employee',
        employeeId: employee.employeeNumber,
        dept,
        position,
        isFirstLogin: true,
        isActive: true,
        isIntern,
        status: 'PENDING_ACTIVATION',
        activationToken,
        tokenExpiry,
        isEmailVerified: false,
      },
    });
    
    console.log('✅ User created:', user.email, 'Role:', user.role);
    
    // Send activation email
    const emailResult = await sendActivationEmail(email, fullName, activationToken);
    
    return NextResponse.json({
      success: true,
      message: `Employee ${fullName} created successfully!`,
      empNumber: employee.employeeNumber,
      username: username,
      tempPassword: tempPassword,
      emailSent: emailResult?.success || false,
      requiresActivation: true,
    }, { status: 201 });
    
  } catch (error) {
    console.error('Error creating employee:', error);
    return NextResponse.json(
      { error: error instanceof Error ? error.message : 'Internal Server Error' },
      { status: 500 }
    );
  }
}