import * as plugins from '../plugins.js';
import * as paths from '../paths.js';
import { logger } from '../logger.js';
import type { SzPlatformService } from '../platformservice.js';

export interface ISmsConstructorOptions {
  apiGatewayApiToken: string;
}

export class SmsService {
  public platformServiceRef: SzPlatformService;
  public projectinfo: plugins.projectinfo.ProjectInfo;
  public typedrouter = new plugins.typedrequest.TypedRouter();
  public options: ISmsConstructorOptions;

  constructor(platformServiceRefArg: SzPlatformService, optionsArg: ISmsConstructorOptions) {
    this.platformServiceRef = platformServiceRefArg;
    this.options = optionsArg;
    this.platformServiceRef.typedrouter.addTypedRouter(this.typedrouter);
  }

  /**
   * starts the financeflow instance
   */
  public async start() {
    logger.log('info', `starting sms service`);
    this.projectinfo = new plugins.projectinfo.ProjectInfo(paths.packageDir);
    this.typedrouter.addTypedHandler(
      new plugins.typedrequest.TypedHandler<plugins.servezoneInterfaces.platformservice.sms.IRequest_SendSms>(
        'sendSms',
        async (reqData) => {
          await this.sendSms(reqData.toNumber, reqData.fromName, reqData.messageText);
          return {
            status: 'ok',
          };
        }
      )
    );
    this.typedrouter.addTypedHandler(
      new plugins.typedrequest.TypedHandler<plugins.servezoneInterfaces.platformservice.sms.IRequest_SendVerificationCode>(
        'sendVerificationCode',
        async (reqData) => {
          const verificationCode = (
            await this.sendVerificationCode(reqData.toNumber, reqData.fromName)
          ).toString();
          return {
            status: 'ok',
            verificationCode,
          };
        }
      )
    );
  }

  public async sendSms(toNumber: number, fromName: string, messageText: string) {
    const payload = {
      sender: fromName,
      message: messageText,
      recipients: [{ msisdn: toNumber }],
    };

    const resp = await plugins.smartrequest.request('https://gatewayapi.com/rest/mtsms', {
      method: 'POST',
      requestBody: JSON.stringify(payload),
      headers: {
        Authorization: `Basic ${Buffer.from(`${this.options.apiGatewayApiToken}:`).toString('base64')}`,
        'Content-Type': 'application/json',
      },
    });
    const json = await resp.body;
    logger.log('info', `sent an sms to ${toNumber} with text '${messageText}'`, {
      eventType: 'sentSms',
      sms: {
        fromName: fromName,
        toNumber: toNumber.toString(),
        messageText: messageText,
      },
    });
    console.log(JSON.stringify(json, null, 2));
  }

  public async sendVerificationCode(toNumber: number, fromName: string) {
    let verificationCode = Math.floor(100000 + Math.random() * 900000);
    await this.sendSms(toNumber, fromName, `Your verification code: ${verificationCode}`);
    return verificationCode;
  }

  public async stop() {}
}