import { Types } from 'mongoose';

import { Whatsapp } from '@/modules/communication/whatsapp/whatsapp.model';
import { syncWhatsappTemplates } from './whatsapp.helper';
import { Company } from '@/modules/company/company.model';
import { ApiError } from '@/shared/utils/errors';
import { defaultStatus } from '@/shared/utils/responseCode/httpStatusAlias';
import responseCodes from '@/shared/utils/responseCode/responseCode';
import { getObjectId } from '@/shared/utils/commonHelper';

const { WhatsappResponseCodes } = responseCodes;

const DESIRED_TEMPLATE_NAMES = new Set([
  'builder_project_launch',
  'builder_festive_offer',
  'sitevisit_campaign',
  'ready_to_move_campaign',
  'broker_property_campaign',
]);
export const queryWhatsapps = async (
  filter: Record<string, string> = {},
  options = {},
  companyId?: Types.ObjectId | string,
) => {
  const { search, ...rest } = filter;

  const creds = await syncWhatsappTemplates(
    Whatsapp,
    Company,
    companyId,
    WhatsappResponseCodes.WHATSAPP_ERROR,
  );

  const query: Record<string, unknown> = {
    ...rest,
    ...(search && {
      name: { $regex: search, $options: 'i' },
    }),
    companyId: getObjectId(companyId),
    name: { $nin: Array.from(DESIRED_TEMPLATE_NAMES) },
  };

  const whatsapp = await Whatsapp.paginate(query, options);

  return {
    ...whatsapp,
    whatsapp: creds,
  };
};

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

  return true;
};

export const addWhatsappCreds = async (
  companyId: Types.ObjectId,
  data: Record<string, unknown>,
) => {
  const updateFields: Record<string, unknown> = {};
  Object.keys(data).forEach((key) => {
    updateFields[`whatsapp.${key}`] = data[key];
  });

  const updateCompany = await Company.findByIdAndUpdate(
    companyId,
    { $set: updateFields },
    { new: true },
  );

  if (!updateCompany)
    throw new ApiError(
      defaultStatus.INTERNAL_SERVER_ERROR,
      'Company not found',
      true,
      '',
      WhatsappResponseCodes.COMPANY_NOT_FOUND,
    );
};
