import { BadRequestException, Injectable } from '@nestjs/common';
import { ConfigService } from '@nestjs/config';
import axios from 'axios';
import { randomUUID } from 'crypto';
import dayjs from 'dayjs';
import { MokClientService } from './mok-client.service';

/**
 * [드림시큐리티] 본인인증 서비스 구현체
 * docs: https://manager.mobile-ok.com/guide/mok_api_guide/
 */
@Injectable()
export class MokAuthService {
  private origin?: string;
  private prefixId?: string;

  constructor(
    private configService: ConfigService,
    private mokClientService: MokClientService,
  ) {
    this.origin = this.configService.get('mok.origin');
    this.prefixId = this.configService.get('mok.prefixId');
  }

  token() {
    const tid =
      this.prefixId + randomUUID() + '|' + dayjs().format('YYYYMMDDHHmmss');
      
    return {
      /* 본인확인 서비스 용도 */
      /* 01001 : 회원가입, 01002 : 정보변경, 01003 : ID찾기, 01004 : 비밀번호찾기, 01005 : 본인확인용, 01006 : 성인인증, 01007 : 상품구매/결제, 01999 : 기타 */
      usageCode: '01005',
      /* 본인확인 서비스 ID */
      serviceId: this.mokClientService.serviceId,
      /* 암호화된 본인확인 거래 요청 정보 */
      encryptReqClientInfo: this.mokClientService.encrypt(tid),
      /* 이용상품 코드 */
      /* 이용상품 코드, telcoAuth : 휴대폰본인확인 (SMS인증시 인증번호 발송 방식 "SMS")*/
      /* 이용상품 코드, telcoAuth-LMS : 휴대폰본인확인 (SMS인증시 인증번호 발송 방식 "LMS")*/
      serviceType: 'telcoAuth',
      /* 본인확인 결과 타입 */
      /* 본인확인 결과 타입, "MOKToken"  : 개인정보 응답결과를 이용기관 서버에서 본인확인 서버에 요청하여 수신 후 처리 */
      retTransferType: 'MOKToken',
      /* 본인확인 결과 수신 URL */
      returnUrl: this.configService.get('mok.returnUrl'),
    };
  }

  result(data: string) {
    return `https://${this.configService.get('user.baseUrl')}/mok-auth/result?data=${data}`;
  }

  async decrypt(token: string) {
    const decodedToken = decodeURIComponent(token);
    const parsedToken = JSON.parse(decodedToken);

    const authResultRequestObject = {
      encryptMOKKeyToken: parsedToken.encryptMOKKeyToken,
    };
    const endpoint = this.configService.get('mok.resultAuthEndPoint');
    const res = await axios.post(
      this.origin + endpoint,
      authResultRequestObject,
    );
    console.log(res.data);
    if (res.data.resultCode && res.data.resultCode !== '2000') {
      throw new BadRequestException({
        code: 'E9999',
        message: res.data.resultMsg,
      });
    }

    return this.mokClientService.getResult(res.data.encryptMOKResult);
  }
}
