import { Injectable } from '@nestjs/common';
import { DataSource } from 'typeorm';
import { TermsVersion } from '../../features/terms/types/types';
import { Term } from './entity/term.entity';
import { TERM_TYPE } from '../../constants';
import { TermInfoNotFoundError } from '../users/errors/types';
import { Context } from '../../common/log';

@Injectable()
export class TermsRepositoryService {
  constructor(private dataSource: DataSource) {}

  /*
   * 利用規約の最新バージョンを取得する
   * @returns Term[]
   */
  async getLatestTermsInfo(context: Context): Promise<TermsVersion> {
    return await this.dataSource.transaction(async (entityManager) => {
      const termRepo = entityManager.getRepository(Term);
      const latestEulaInfo = await termRepo.findOne({
        where: {
          document_type: TERM_TYPE.EULA,
        },
        order: {
          id: 'DESC',
        },
        comment: `${context.getTrackingId()}_${new Date().toUTCString()}`,
      });
      const latestPrivacyNoticeInfo = await termRepo.findOne({
        where: {
          document_type: TERM_TYPE.PRIVACY_NOTICE,
        },
        order: {
          id: 'DESC',
        },
        comment: `${context.getTrackingId()}_${new Date().toUTCString()}`,
      });
      const latestDpaInfo = await termRepo.findOne({
        where: {
          document_type: TERM_TYPE.DPA,
        },
        order: {
          id: 'DESC',
        },
        comment: `${context.getTrackingId()}_${new Date().toUTCString()}`,
      });

      if (!latestEulaInfo || !latestPrivacyNoticeInfo || !latestDpaInfo) {
        throw new TermInfoNotFoundError(
          `Terms info is not found. latestEulaInfo: ${latestEulaInfo},
          latestPrivacyNoticeInfo: ${latestPrivacyNoticeInfo},
          latestDpaInfo: ${latestDpaInfo}`,
        );
      }
      return {
        eulaVersion: latestEulaInfo.version,
        privacyNoticeVersion: latestEulaInfo.version,
        dpaVersion: latestDpaInfo.version,
      };
    });
  }
}
