import axiosInstance from '@/utils/axios';
import type {
  IEmployee,
  CreateEmployeeRequest,
  UpdateEmployeeRequest,
} from '@/shared/types/employee';

const endpointPrefix = '/api/hr/employees';

export const employeesEndpoints = {
  base: endpointPrefix,
  byId: (id: string) => `${endpointPrefix}/${id}`,
  copyEmployee: (id: string) => `${endpointPrefix}/${id}/copy`,
};

// Employee API endpoints
export const employeesApi = {
  getAllEmployees: (params: {
    lastName?: string;
    firstName?: string;
    email?: string;
    phone?: string;
    employeeNumber?: string;
    department?: string;
    status?: string;
    type?: string;
    registrationDateFrom?: string;
    registrationDateTo?: string;
    searchTerm?: string;
    page?: number;
    size?: number;
    sortBy?: string;
    sortDirection?: string;
  }) => {
    const searchParams = new URLSearchParams();

    Object.entries(params).forEach(([key, value]) => {
      if (value !== undefined && value !== null && value !== '') {
        searchParams.append(key, String(value));
      }
    });

    return axiosInstance.get(`${endpointPrefix}?${searchParams.toString()}`);
  },

  getEmployeeById: (id: string) => axiosInstance.get(employeesEndpoints.byId(id)),
  createEmployee: (data: CreateEmployeeRequest) => {
    const formData = new FormData();
    Object.entries(data).forEach(([key, value]) => {
      if (value !== undefined && value !== null && !key.includes('File')) {
        if (value instanceof Date) {
          formData.append(key, value.toISOString().split('T')[0]);
        } else {
          formData.append(key, String(value));
        }
      }
    });

    // Add file fields
    if (data.profilePictureFile) {
      formData.append('profilePictureFile', data.profilePictureFile);
    }
    if (data.healthCardFile) {
      formData.append('healthCardFile', data.healthCardFile);
    }
    if (data.bankDetailsFile) {
      formData.append('bankDetailsFile', data.bankDetailsFile);
    }
    if (data.licenseFile) {
      formData.append('licenseFile', data.licenseFile);
    }
    if (data.idCardFile) {
      formData.append('idCardFile', data.idCardFile);
    }

    return axiosInstance.post(employeesEndpoints.base, formData, {
      headers: {
        'Content-Type': 'multipart/form-data',
      },
    });
  },

  // Update employee with file uploads
  updateEmployee: (id: string, data: UpdateEmployeeRequest) => {
    const formData = new FormData();

    // Add text fields
    Object.entries(data).forEach(([key, value]) => {
      if (
        value !== undefined &&
        value !== null &&
        !key.includes('File') &&
        !key.includes('existing')
      ) {
        if (value instanceof Date) {
          formData.append(key, value.toISOString().split('T')[0]);
        } else {
          formData.append(key, String(value));
        }
      }
    });

    // Add existing document paths
    if (data.existingProfilePicturePath) {
      formData.append('existingProfilePicturePath', data.existingProfilePicturePath);
    }
    if (data.existingHealthCardPath) {
      formData.append('existingHealthCardPath', data.existingHealthCardPath);
    }
    if (data.existingBankDetailsPath) {
      formData.append('existingBankDetailsPath', data.existingBankDetailsPath);
    }
    if (data.existingLicensePath) {
      formData.append('existingLicensePath', data.existingLicensePath);
    }
    if (data.existingIdCardPath) {
      formData.append('existingIdCardPath', data.existingIdCardPath);
    }
    if (data.profilePictureFile) {
      formData.append('profilePictureFile', data.profilePictureFile);
    }
    if (data.healthCardFile) {
      formData.append('healthCardFile', data.healthCardFile);
    }
    if (data.bankDetailsFile) {
      formData.append('bankDetailsFile', data.bankDetailsFile);
    }
    if (data.licenseFile) {
      formData.append('licenseFile', data.licenseFile);
    }
    if (data.idCardFile) {
      formData.append('idCardFile', data.idCardFile);
    }

    return axiosInstance.put(employeesEndpoints.byId(id), formData, {
      headers: {
        'Content-Type': 'multipart/form-data',
      },
    });
  },

  deleteEmployee: (id: string) => axiosInstance.delete(employeesEndpoints.byId(id)),
  changeEmployeeStatus: (id: string, status: string) => {
    return axiosInstance.patch(`${employeesEndpoints.byId(id)}/status`, null, {
      params: { status },
    });
  },
  copyEmployee: (id: string) => {
    return axiosInstance.post(employeesEndpoints.copyEmployee(id));
  },
};
