import { Injectable, Logger } from '@nestjs/common';
import { ConfigService } from '@nestjs/config';
import {
  NotificationHubsClient,
  createWindowsRegistrationDescription,
  RegistrationDescription,
  createAppleRegistrationDescription,
} from '@azure/notification-hubs';
@Injectable()
export class NotificationhubService {
  private readonly logger = new Logger(NotificationhubService.name);
  private readonly client: NotificationHubsClient;
  constructor(private readonly configService: ConfigService) {
    this.client = new NotificationHubsClient(
      this.configService.get<string>('NOTIFICATION_HUB_CONNECT_STRING'),
      this.configService.get<string>('NOTIFICATION_HUB_NAME'),
    );
  }

  /**
   * Registers notificationhub service
   * @param pns
   * @param pnsHandler
   * @returns register
   */
  async register(pns: string, pnsHandler: string): Promise<void> {
    this.logger.log(`[IN] ${this.register.name}`);
    let reg: RegistrationDescription;
    //登録情報作成
    try {
      if (pns === 'wns') {
        reg = createWindowsRegistrationDescription({
          channelUri: pnsHandler,
          tags: [],
          // XXX [Task2218] 登録の有効期限を設定したい場合等、本実装を別途Taskで行う
          //expirationTime: '',
        });
      } else if (pns === 'apns') {
        reg = createAppleRegistrationDescription({
          deviceToken: pnsHandler,
          tags: [],
        });
      } else {
        throw new Error('invalid pns');
      }
    } catch (e) {
      this.logger.error(`error=${e.message}`);
      throw e;
    } finally {
      this.logger.log(`[OUT] ${this.register.name}`);
    }

    try {
      //登録
      await this.client.createOrUpdateRegistration(reg);
    } catch (e) {
      this.logger.error(`error=${e}`);
      throw e;
    } finally {
      this.logger.log(`[OUT] ${this.register.name}`);
    }
  }
}
