// otp.service.ts

import {
  BadRequestException,
  Injectable,
} from "@nestjs/common";

import axios from "axios";

import { OtpRepository } from "./otp.repository";

@Injectable()
export class OtpService {
  constructor(
    private readonly otpRepository: OtpRepository
  ) {}

  // ---------------------------------------------------------------------------
  // Generate OTP
  // ---------------------------------------------------------------------------

  generateOtp(): string {
    return Math.floor(
      100000 + Math.random() * 900000
    ).toString();
  }

  // ---------------------------------------------------------------------------
  // Send OTP
  // ---------------------------------------------------------------------------

  async sendOtp(phone: string, otp: string) {
    try {
      // generate otp
      // const otp =
      //   this.generateOtp();

      // find existing phone
      const existingPhone =
        await this.otpRepository.findByPhone(
          phone
        );

      // update existing otp
      if (existingPhone) {
        await this.otpRepository.updateOtp(
          existingPhone,
          otp
        );
      } else {
        // create new otp
        await this.otpRepository.createOtp(
          phone,
          otp
        );
      }

      // send sms
      await axios.post(
        "https://notification-dev.license.aafda.gov.et/api/sms-services/ozeking/sms",
        {
          to: phone,

          sourceId: "EDR",

          sourceName:
            "EDR Freight",

          appKey:
            "YOUR_APP_KEY",

          text: `Your verification code is ${otp}`,

          callbackUrl: "",
        },
        {
          headers: {
            accept: "*/*",

            "Content-Type":
              "application/json",
          },
        }
      );

      return {
        success: true,

        message:
          "OTP sent successfully",
      };
    } catch (error) {
      console.log(error);

      throw new BadRequestException(
        "Failed to send OTP"
      );
    }
  }

  // ---------------------------------------------------------------------------
  // Verify OTP
  // ---------------------------------------------------------------------------

  async verifyOtp(
    phone: string,
    otp: string
  ) {
    // find phone
    const otpData =
      await this.otpRepository.findByPhone(
        phone
      );

    // phone not found
    if (!otpData) {
      throw new BadRequestException(
        "Phone number not found"
      );
    }

    // invalid otp
    if (otpData.otp !== otp) {
      throw new BadRequestException(
        "Invalid OTP"
      );
    }

    // verify phone
    await this.otpRepository.verifyPhone(
      otpData
    );

    return {
      success: true,

      message:
        "Phone verified successfully",
    };
  }
}