/* eslint-disable camelcase */

import axios from 'axios';
import { Types } from 'mongoose';

import { Fast2sms } from '@/modules/communication/fast2sms/fast2sms.model';
import config from '../config/config';
import { Company } from '@/modules/company/company.model';
import { getSuperAdminCompanyId } from '@/modules/communication/fast2sms/fast2sms.helper';
import { ICompanyDoc } from '@/modules/company/company.interface';
import { TriggerPoint } from '../constants/enum.constant';

export async function sendFast2smsMessage(
  companyId: string | Types.ObjectId,
  triggerPoint: string,
  phoneNumber: string,
  variablesValues?: string[],
) {
  const isLoginOTP = triggerPoint === TriggerPoint.OnLoginMobileApp;

  try {
    // 1️⃣ Load company
    const company = (await Company.findById(companyId).select(
      'fast2sms.senderId smsCredit',
    )) as ICompanyDoc | null;

    if (!company) {
      console.error(`Company not found for id ${companyId}`);
      return false;
    }

    const hasCompanySender = Boolean(company.fast2sms?.senderId);
    const needsCredit = !hasCompanySender && !isLoginOTP;

    // 2️⃣ Credit check (only one place)
    if (needsCredit && (!company.smsCredit || company.smsCredit <= 0)) {
      console.error(`Insufficient SMS credits for company ${companyId}`);
      return false;
    }

    // 3️⃣ Resolve senderId
    let senderId = company.fast2sms?.senderId;

    if (!senderId) {
      const superAdmin = (await getSuperAdminCompanyId()) as ICompanyDoc;

      if (!superAdmin?.fast2sms?.senderId) {
        console.error('No SMS senderId available');
        return false;
      }

      senderId = superAdmin.fast2sms.senderId;
    }

    // 4️⃣ Fetch template
    const templates = await Fast2sms.find({
      companyId,
      triggerPoint,
      status: 'active',
    });

    if (!templates.length) {
      console.error(`No active SMS template for ${triggerPoint}`);
      return false;
    }

    const template =
      templates.find((t) => !t.isDefault) || templates.find((t) => t.isDefault);

    if (!template) {
      console.error('No suitable SMS template found');
      return false;
    }

    // 5️⃣ Build payload
    const payload: any = {
      route: config.fast2sms.route,
      sender_id: senderId,
      message: template.templateId,
      flash: 0,
      numbers: String(phoneNumber),
    };

    if (variablesValues?.length) 
      payload.variables_values = variablesValues.join('|');
    

    // 6️⃣ Send SMS
    const response = await axios.post(config.fast2sms.apiUrl, payload, {
      headers: {
        authorization: config.fast2sms.apiKey,
        'Content-Type': 'application/json',
      },
      timeout: 15000,
    });

    if (!response.data?.return) {
      console.error(
        `Fast2SMS failed: ${response.data?.message || 'Unknown error'}`,
      );
      return false;
    }

    // 7️⃣ Deduct credit (single clear rule)
    if (needsCredit) 
      await Company.findByIdAndUpdate(companyId, {
        $inc: { smsCredit: -1 },
      });
    

    return response.data;
  } catch (error: any) {
    if (error?.code === 'ETIMEDOUT') {
      console.warn('Fast2SMS timeout – message may still be delivered');
      return true;
    }

    console.error('Fast2SMS error:', error.message);
    return false;
  }
}
