import { ApiError } from '@/shared/utils/errors';
import { defaultStatus } from '@/shared/utils/responseCode/httpStatusAlias';
import responseCodes from '@/shared/utils/responseCode/responseCode';

import { SubCompany } from '@/modules/subCompany/subCompany.model';
import { ISubCompanyDoc, NewCreatedSubCompany, UpdateSubCompanyBody } from '@/modules/subCompany/subCompany.interface';

const { SubCompanyResponseCodes } = responseCodes;

export const createSubCompany = async (data: NewCreatedSubCompany): Promise<ISubCompanyDoc | null> => {
  let subCompany: ISubCompanyDoc | null;

  try {
    subCompany = await SubCompany.create(data);
  } catch (_error) {
    throw new ApiError(defaultStatus.OK, 'Failed to create subCompany', true, '', SubCompanyResponseCodes.COMPANY_ERROR);
  }

  return subCompany;
};

export const getSubCompanyById = async (id: string) => {
  const subCompany = await SubCompany.findById(id);
  if (!subCompany)
    throw new ApiError(defaultStatus.OK, 'SubCompany not found', true, '', SubCompanyResponseCodes.COMPANY_NOT_FOUND);

  return subCompany;
};

export const updateSubCompany = async (id: string, updateData: UpdateSubCompanyBody): Promise<boolean | null> => {
  let subCompany: boolean | null;

  try {
    subCompany = await SubCompany.findByIdAndUpdate(id, updateData, { new: true });
  } catch (_error) {
    throw new ApiError(defaultStatus.OK, 'Failed to update subCompany', true, '', SubCompanyResponseCodes.COMPANY_ERROR);
  }

  if (!subCompany)
    throw new ApiError(defaultStatus.OK, 'SubCompany not found', true, '', SubCompanyResponseCodes.COMPANY_NOT_FOUND);

  return true;
};

export const deleteSubCompany = async (id: string): Promise<boolean | null> => {
  let subCompany: boolean | null;
  try {
    subCompany = await SubCompany.findByIdAndDelete(id);
  } catch (_error) {
    throw new ApiError(defaultStatus.OK, 'Failed to delete subCompany', true, '', SubCompanyResponseCodes.COMPANY_ERROR);
  }

  if (!subCompany)
    throw new ApiError(defaultStatus.OK, 'SubCompany not found', true, '', SubCompanyResponseCodes.COMPANY_NOT_FOUND);

  return true;
};

export const querySubCompanies = async (filter = {}, options = {}) => SubCompany.paginate(filter, options);
