import {
  Body,
  Controller,
  HttpException,
  HttpStatus,
  Logger,
  Post,
  Req,
  UseGuards,
} from '@nestjs/common';
import {
  ApiResponse,
  ApiOperation,
  ApiBearerAuth,
  ApiTags,
} from '@nestjs/swagger';
import { Request } from 'express';
import { ErrorResponse } from '../../common/error/types/types';
import { RegisterRequest, RegisterResponse } from './types/types';
import { NotificationService } from './notification.service';
import { AuthGuard } from '../../common/guards/auth/authguards';
import { retrieveAuthorizationToken } from '../../common/http/helper';
import { AccessToken } from '../../common/token';
import jwt from 'jsonwebtoken';
import { makeContext, retrieveRequestId, retrieveIp } from '../../common/log';
import { makeErrorResponse } from '../../common/error/makeErrorResponse';

@ApiTags('notification')
@Controller('notification')
export class NotificationController {
  private readonly logger = new Logger(NotificationController.name);
  constructor(private readonly notificationService: NotificationService) {}
  @Post('register')
  @ApiResponse({
    status: HttpStatus.OK,
    type: RegisterResponse,
    description: '成功時のレスポンス',
  })
  @ApiResponse({
    status: HttpStatus.BAD_REQUEST,
    description: '不正なパラメータ',
    type: ErrorResponse,
  })
  @ApiResponse({
    status: HttpStatus.UNAUTHORIZED,
    description: '認証エラー',
    type: ErrorResponse,
  })
  @ApiResponse({
    status: HttpStatus.INTERNAL_SERVER_ERROR,
    description: '想定外のサーバーエラー',
    type: ErrorResponse,
  })
  @ApiOperation({ operationId: 'register' })
  @ApiBearerAuth()
  @UseGuards(AuthGuard)
  async register(
    @Req() req: Request,
    @Body() body: RegisterRequest,
  ): Promise<RegisterResponse> {
    const { handler, pns } = body;

    const accessToken = retrieveAuthorizationToken(req);
    if (!accessToken) {
      throw new HttpException(
        makeErrorResponse('E000107'),
        HttpStatus.UNAUTHORIZED,
      );
    }

    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 decodedAccessToken = jwt.decode(accessToken, { json: true });
    if (!decodedAccessToken) {
      throw new HttpException(
        makeErrorResponse('E000101'),
        HttpStatus.UNAUTHORIZED,
      );
    }
    const { userId } = decodedAccessToken as AccessToken;

    const context = makeContext(userId, requestId);
    this.logger.log(`[${context.getTrackingId()}] ip : ${ip}`);

    await this.notificationService.register(context, userId, pns, handler);
    return {};
  }
}
