import { Types } from 'mongoose';

import { Email } from '@/modules/communication/email/email.model';
import { syncEmailTemplates } from './email.helper';
import responseCodes from '@/shared/utils/responseCode/responseCode';
import { ApiError } from '@/shared/utils/errors';
import { defaultStatus } from '@/shared/utils/responseCode/httpStatusAlias';
import { Status } from '@/shared/constants/enum.constant';
import { getObjectId } from '@/shared/utils/commonHelper';

const { EmailResponseCodes } = responseCodes;
export const queryEmail = async (
  filter: Record<string, string> = {},
  options = {},
  companyId?: Types.ObjectId | string,
) => {
  try {
    const { search, ...rest } = filter;

    const emailCredits = await syncEmailTemplates(companyId, true);

    const query: Record<string, unknown> = {
      ...rest,
      ...(search && {
        name: { $regex: search, $options: 'i' },
      }),
      emailStatus: Status.ACTIVE,
      companyId: getObjectId(companyId),
    };

    const email = await Email.paginate(query, options);

    return { ...email, emailCredits };
  } catch (e) {
    console.log(e);
    throw new ApiError(
      defaultStatus.INTERNAL_SERVER_ERROR,
      'Failed to sync email templates',
      true,
      '',
      EmailResponseCodes.EMAIL_ERROR,
    );
  }
};

export const updateTemplate = async (
  id: string,
  data: Record<string, unknown>,
) => {
  await Email.findOneAndUpdate({ _id: id }, { $set: data }, { new: true });

  return true;
};
