import {
  Controller,
  HttpStatus,
  Get,
  Logger,
  HttpException,
  Req,
} from '@nestjs/common';
import { ApiOperation, ApiResponse, ApiTags } from '@nestjs/swagger';
import { TermsService } from '../terms/terms.service';
import { ErrorResponse } from '../../common/error/types/types';
import { makeContext, retrieveRequestId, retrieveIp } from '../../common/log';
import { GetTermsInfoResponse } from './types/types';
import { makeErrorResponse } from '../../common/error/makeErrorResponse';

import { Request } from 'express';

@ApiTags('terms')
@Controller('terms')
export class TermsController {
  private readonly logger = new Logger(TermsController.name);
  constructor(
    private readonly termsService: TermsService, //private readonly cryptoService: CryptoService,
  ) {}

  @Get()
  @ApiResponse({
    status: HttpStatus.OK,
    type: GetTermsInfoResponse,
    description: '成功時のレスポンス',
  })
  @ApiResponse({
    status: HttpStatus.INTERNAL_SERVER_ERROR,
    description: '想定外のサーバーエラー',
    type: ErrorResponse,
  })
  @ApiOperation({ operationId: 'getTermsInfo' })
  async getTermsInfo(@Req() req: Request): Promise<GetTermsInfoResponse> {
    const ip = retrieveIp(req);
    if (!ip) {
      throw new HttpException(
        makeErrorResponse('E000401'),
        HttpStatus.UNAUTHORIZED,
      );
    }

    const requestId = retrieveRequestId(req);
    if (!requestId) {
      throw new HttpException(
        makeErrorResponse('E000501'),
        HttpStatus.INTERNAL_SERVER_ERROR,
      );
    }
    const context = makeContext('anonymous', requestId);
    this.logger.log(`[${context.getTrackingId()}] ip : ${ip}`);

    const termsInfo = await this.termsService.getTermsInfo(context);

    return { termsInfo };
  }
}
