﻿import { NextRequest, NextResponse } from 'next/server';
import prisma from '@/lib/prisma';

// GET - Fetch employee profile
export async function GET(request: NextRequest) {
  try {
    const { searchParams } = new URL(request.url);
    const employeeId = searchParams.get('employeeId');
    const email = searchParams.get('email');
    
    // Find by either employeeId or email
    let employee = null;
    
    if (employeeId) {
      employee = await prisma.employee.findFirst({
        where: {
          OR: [
            { employeeNumber: employeeId },
            { id: employeeId },
          ]
        }
      });
    } else if (email) {
      employee = await prisma.employee.findUnique({
        where: { email: email }
      });
    }
    
    if (!employee) {
      return NextResponse.json({});
    }
    
    return NextResponse.json(employee);
  } catch (error) {
    console.error('Error fetching employee profile:', error);
    return NextResponse.json({ error: 'Failed to fetch profile' }, { status: 500 });
  }
}

// PUT - Update employee profile
export async function PUT(request: NextRequest) {
  try {
    const body = await request.json();
    const { 
      employeeId, 
      email, 
      phone, 
      dob, 
      address, 
      physicalAddress,
      emergencyContact, 
      emergencyContactName,
      emergencyPhone, 
      bloodGroup,
      institution,
      course,
      yearOfStudy,
      attachmentStartDate,
      attachmentEndDate,
      directSupervisor,
      nationalId,
      kraPin,
      fullName,
      dept,
      position,
      gender,
      ...otherData 
    } = body;
    
    // Find the employee first
    let employee = null;
    
    if (employeeId) {
      employee = await prisma.employee.findFirst({
        where: {
          OR: [
            { employeeNumber: employeeId },
            { id: employeeId },
          ]
        }
      });
    } else if (email) {
      employee = await prisma.employee.findUnique({
        where: { email: email }
      });
    }
    
    if (!employee) {
      return NextResponse.json({ error: 'Employee not found' }, { status: 404 });
    }
    
    // Prepare update data
    const updateData: any = {};
    
    // Basic fields
    if (phone !== undefined) updateData.phone = phone || null;
    if (dob !== undefined) updateData.dob = dob ? new Date(dob) : null;
    if (address !== undefined) updateData.address = address || null;
    if (physicalAddress !== undefined) updateData.physicalAddress = physicalAddress || null;
    if (emergencyContact !== undefined) updateData.emergencyContact = emergencyContact || null;
    if (emergencyContactName !== undefined) updateData.emergencyContactName = emergencyContactName || null;
    if (emergencyPhone !== undefined) updateData.emergencyPhone = emergencyPhone || null;
    if (bloodGroup !== undefined) updateData.bloodGroup = bloodGroup || null;
    
    // Profile fields
    if (institution !== undefined) updateData.institution = institution || null;
    if (course !== undefined) updateData.course = course || null;
    if (yearOfStudy !== undefined) updateData.yearOfStudy = yearOfStudy || null;
    if (attachmentStartDate !== undefined) updateData.attachmentStartDate = attachmentStartDate ? new Date(attachmentStartDate) : null;
    if (attachmentEndDate !== undefined) updateData.attachmentEndDate = attachmentEndDate ? new Date(attachmentEndDate) : null;
    if (directSupervisor !== undefined) updateData.directSupervisor = directSupervisor || null;
    if (nationalId !== undefined) updateData.nationalId = nationalId || null;
    if (kraPin !== undefined) updateData.kraPin = kraPin || null;
    
    // Employee basic info
    if (fullName !== undefined) {
      updateData.fullName = fullName;
      const nameParts = fullName.trim().split(' ');
      updateData.firstName = nameParts[0];
      updateData.lastName = nameParts.slice(1).join(' ') || '';
    }
    if (dept !== undefined) updateData.dept = dept;
    if (position !== undefined) updateData.position = position;
    if (gender !== undefined) updateData.gender = gender;
    
    // Also allow updating other fields if needed
    if (otherData.firstName) updateData.firstName = otherData.firstName;
    if (otherData.lastName) updateData.lastName = otherData.lastName;
    if (otherData.employmentType) updateData.employmentType = otherData.employmentType;
    if (otherData.isActive !== undefined) updateData.isActive = otherData.isActive;
    
    // Update the employee
    const updatedEmployee = await prisma.employee.update({
      where: { id: employee.id },
      data: updateData
    });
    
    // Also update the user record if name, email, dept, or position changed
    const userUpdateData: any = {};
    if (updateData.fullName) userUpdateData.name = updateData.fullName;
    if (otherData.email) userUpdateData.email = otherData.email;
    if (updateData.dept) userUpdateData.dept = updateData.dept;
    if (updateData.position) userUpdateData.position = updateData.position;
    
    if (Object.keys(userUpdateData).length > 0) {
      await prisma.user.updateMany({
        where: { email: employee.email },
        data: userUpdateData
      });
    }
    
    return NextResponse.json({ 
      success: true, 
      message: 'Profile updated successfully',
      employee: updatedEmployee 
    });
  } catch (error) {
    console.error('Error updating employee profile:', error);
    return NextResponse.json({ 
      error: error instanceof Error ? error.message : 'Failed to update profile' 
    }, { status: 500 });
  }
}

// PATCH - Partially update employee profile (for single fields)
export async function PATCH(request: NextRequest) {
  try {
    const body = await request.json();
    const { employeeId, field, value } = body;
    
    if (!employeeId || !field) {
      return NextResponse.json({ error: 'Employee ID and field are required' }, { status: 400 });
    }
    
    // Find the employee
    const employee = await prisma.employee.findFirst({
      where: {
        OR: [
          { employeeNumber: employeeId },
          { id: employeeId },
          { email: employeeId }
        ]
      }
    });
    
    if (!employee) {
      return NextResponse.json({ error: 'Employee not found' }, { status: 404 });
    }
    
    // Prepare update data based on field type
    let updateValue: any = value;
    if (field === 'dob' && value) {
      updateValue = new Date(value);
    }
    if ((field === 'attachmentStartDate' || field === 'attachmentEndDate') && value) {
      updateValue = new Date(value);
    }
    
    // Handle field name mappings
    let dbField = field;
    if (field === 'physicalAddress') dbField = 'physicalAddress';
    if (field === 'emergencyContactName') dbField = 'emergencyContactName';
    if (field === 'directSupervisor') dbField = 'directSupervisor';
    
    // Update the specific field
    const updatedEmployee = await prisma.employee.update({
      where: { id: employee.id },
      data: { [dbField]: updateValue }
    });
    
    return NextResponse.json({ 
      success: true, 
      message: 'Field updated successfully',
      employee: updatedEmployee 
    });
  } catch (error) {
    console.error('Error patching employee profile:', error);
    return NextResponse.json({ error: 'Failed to update profile' }, { status: 500 });
  }
}