

import { Injectable } from '@nestjs/common';
import axios from 'axios';

@Injectable()
export class TwilioService {
  private readonly accountSid: string;
  private readonly authToken: string;
  private readonly serviceSid: string;
  private readonly basicAuth: string;

  constructor() {
    this.accountSid = process.env.TWILIO_ACCOUNT_SID;
    this.authToken = process.env.TWILIO_AUTH_TOKEN;
    this.serviceSid = process.env.TWILIO_SERVICE_SID;
    this.basicAuth = Buffer.from(`${this.accountSid}:${this.authToken}`).toString('base64');
  }

  async sendOtp(toPhoneNumber: string): Promise<any> {
    const url = `https://verify.twilio.com/v2/Services/${this.serviceSid}/Verifications`;

    const data = new URLSearchParams({
      To: toPhoneNumber,
      Channel: 'sms',
    });

    try {
      const response = await axios.post(url, data.toString(), {
        headers: {
          'Content-Type': 'application/x-www-form-urlencoded',
          'Authorization': `Basic ${this.basicAuth}`,
        },
      });

      return response.data;
    } catch (error) {
      return error;
    }
  }

  async verifyOtp(toPhoneNumber: string, otpCode: string): Promise<any> {
    const url = `https://verify.twilio.com/v2/Services/${this.serviceSid}/VerificationCheck`;

    const data = new URLSearchParams({
      To: toPhoneNumber,
      Code: otpCode,
    });

    try {
      const response = await axios.post(url, data.toString(), {
        headers: {
          'Content-Type': 'application/x-www-form-urlencoded',
          'Authorization': `Basic ${this.basicAuth}`,
        },
      });
      return response.data;
    } catch (error) {
      console.error('Error verifying OTP:', error.response?.data ?? error.message);
      throw error;
    }
  }
}

