import { EmployeeModel, employeeValidationSchema } from "../models/employee";
import { Request, Response } from "express";
import { Op } from "sequelize";

/// Create new employee
export const createEmployee = async (req: Request, res: Response) => {
  console.log("Request Body:", req.body);
  const { error } = employeeValidationSchema.validate(req.body);
  if (error) return res.status(400).json({ error: error.details[0].message });

  try {
    // Check if email already exists
    const existingEmployee = await EmployeeModel.findOne({
      where: { email: req.body.email },
    });
    if (existingEmployee)
      return res.status(400).json({ error: "Email address already exists." });

    const newEmployee = await EmployeeModel.create(req.body);
    return res
      .status(200)
      .json({ message: "Employee created successfully.", id: newEmployee.id });
  } catch (ex) {
    // return res.status(500).json({ error: "An unexpected error occurred." });
    return res.status(500).json({ error: ex });
  }
};

/// Get all employees
export const getAllEmployees = async (req: Request, res: Response) => {
  try {
    const employees = await EmployeeModel.findAll({
      where: { isDeleted: false },
    });
    return res.status(200).json(employees);
  } catch (ex) {
    return res.status(500).json({ error: "An unexpected error occurred." });
  }
};

/// Update existing employee
export const updateEmployee = async (req: Request, res: Response) => {
  try {
    // Find the employee by ID
    const employee = await EmployeeModel.findByPk(req.params.id);
    if (!employee)
      return res.status(404).json({ error: "Employee not found." });

    // Check if updating email and it already exists
    if (req.body.email) {
      const existingEmployee = await EmployeeModel.findOne({
        where: { email: req.body.email, id: { [Op.ne]: req.params.id } },
      });
      if (existingEmployee)
        return res.status(400).json({ error: "Email address already exists." });
    }

    // Validate the request body
    const { error } = employeeValidationSchema.validate(req.body);
    if (error) return res.status(400).json({ error: error.details[0].message });

    // Update the employee details
    await employee.update(req.body);

    // Send success response
    return res
      .status(200)
      .json({ message: "Employee updated successfully.", id: employee.id });
  } catch (ex) {
    console.error(`Error updating employee: ${ex}`);
    return res.status(500).json({ error: "An unexpected error occurred." });
  }
};

/// Delete an employee
export const deleteEmployee = async (req: Request, res: Response) => {
  try {
    // Find the employee by ID
    const employee = await EmployeeModel.findByPk(req.params.id);
    if (!employee)
      return res.status(404).json({ error: "Employee not found." });

    // Soft delete the employee
    await employee.update({ isDeleted: true });

    // Send success response
    return res.status(200).json({ message: "Employee deleted successfully." });
  } catch (ex) {
    return res.status(500).json({ error: "An unexpected error occurred." });
  }
};
