import { HttpException, HttpStatus, Injectable, Logger } from '@nestjs/common';
import { Context } from '../../common/log';
import { makeErrorResponse } from '../../common/error/makeErrorResponse';
import { TermInfo } from './types/types';
import { TermsRepositoryService } from '../../repositories/terms/terms.repository.service';
import { TERM_TYPE } from '../../constants';

@Injectable()
export class TermsService {
  constructor(private readonly termsRepository: TermsRepositoryService) {}
  private readonly logger = new Logger(TermsService.name);

  /**
   * 利用規約情報を取得する
   * return termsInfo
   */
  async getTermsInfo(context: Context): Promise<TermInfo[]> {
    this.logger.log(
      `[IN] [${context.getTrackingId()}] ${this.getTermsInfo.name}`,
    );
    try {
      const { eulaVersion, privacyNoticeVersion, dpaVersion } =
        await this.termsRepository.getLatestTermsInfo(context);
      return [
        {
          documentType: TERM_TYPE.EULA,
          version: eulaVersion,
        },
        {
          documentType: TERM_TYPE.PRIVACY_NOTICE,
          version: privacyNoticeVersion,
        },
        {
          documentType: TERM_TYPE.DPA,
          version: dpaVersion,
        },
      ];
    } catch (e) {
      this.logger.error(`[${context.getTrackingId()}] error=${e}`);
      throw new HttpException(
        makeErrorResponse('E009999'),
        HttpStatus.INTERNAL_SERVER_ERROR,
      );
    } finally {
      this.logger.log(
        `[OUT] [${context.getTrackingId()}] ${this.getTermsInfo.name}`,
      );
    }
  }
}
