import {
  Body,
  Controller,
  HttpStatus,
  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 } from '../../common/log';

@ApiTags('notification')
@Controller('notification')
export class NotificationController {
  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);
    const { userId } = jwt.decode(accessToken, { json: true }) as AccessToken;

    const context = makeContext(userId);

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