import { Injectable, HttpException, HttpStatus } from '@nestjs/common';
import { ConfigService } from '@nestjs/config';
import axios from 'axios';
import { ISmsParams, ISmsResponse, ISmsBodyParameters } from '../interfaces/sms';

@Injectable()
export class SmsService {
  private readonly baseURL: string;
  private readonly OTP: string;
  private readonly apiKey: string;

  constructor(
    // private readonly httpService: HttpService,
    private readonly configService: ConfigService,
  ) {
    this.baseURL = this.configService.getOrThrow<string>('SMS_BASE_URL');
    this.apiKey = this.configService.getOrThrow<string>('SMS_API_KEY');
    this.OTP = this.configService.getOrThrow<string>('SMS_PATTERN_OTP');
  }

  sendotp(phone: string, otp: string) {
    return this.sendSms({
      phone,
      parameters: { otp },
      templateId: this.OTP,
    });
  }

  async sendSms(params: ISmsParams) {
    const { parameters, phone, templateId } = params;
    const parametersArray = Object.entries(parameters ?? {}).map(([name, value]) => ({
      name,
      value: value.toString(),
    }));
    const cleanedPhone = this.formatPhone(phone);

    const smsData: ISmsBodyParameters = {
      Parameters: parametersArray,
      Mobile: cleanedPhone,
      TemplateId: templateId,
    };

    const url = `${this.baseURL}/send/verify`;

    try {
      const { data } = await axios.post<ISmsResponse>(url, smsData, {
        headers: {
          'Content-Type': 'application/json',
          'X-API-KEY': this.apiKey,
        },
      });
      if (data.status !== 1) {
        throw new HttpException('The SMS was not sent. Please try again later.', HttpStatus.BAD_GATEWAY);
      }
      return data;
    } catch (error) {
      console.error('SMS sending failed:', JSON.stringify(error));
      throw new HttpException('The SMS was not sent. Please try again later.', HttpStatus.BAD_GATEWAY);
    }
  }
  
  formatPhone(phone: string): string {
    // remove spaces, dashes, parentheses
    phone = phone.replace(/[^\d+]/g, '');

    if (phone.startsWith('+98')) {
      return phone;
    }

    if (phone.startsWith('98')) {
      return `+${phone}`;
    }

    if (phone.startsWith('0')) {
      return `+98${phone.slice(1)}`;
    }

    return `+98${phone}`;
  }
}
