import {
  ExceptionFilter,
  Catch,
  ArgumentsHost,
  HttpException,
  HttpStatus
} from '@nestjs/common';
import { JsonWebTokenError, TokenExpiredError } from '@nestjs/jwt';
import { FastifyReply, FastifyRequest } from 'fastify';
import { UnauthorizedCode, UnauthorizedMessage, BadRequestCode, BadRequestMessage, InternalServerErrorCode, InternalServerErrorMessage } from '@baekyangdan/core-utils';

@Catch()
export class AllExceptionsFilter implements ExceptionFilter {
  catch(exception: unknown, host: ArgumentsHost) {
    const ctx = host.switchToHttp();
    const response = ctx.getResponse<FastifyReply>();
    const request = ctx.getRequest<FastifyRequest>();
    console.log(exception);

    // TokenExpiredError
    if (exception instanceof TokenExpiredError) {
      const status = HttpStatus.UNAUTHORIZED;

      const responseBody = {
        statusCode: status,
        message: UnauthorizedMessage.ACCESS_TOKEN_EXPIRED,
        code: UnauthorizedCode.ACCESS_TOKEN_EXPIRED,
        timestamp: new Date().toISOString(),
        path: ctx.getRequest().url
      };

      response.status(status).send(responseBody);
      return;
    }

    // JsonWebTokenError
    if (exception instanceof JsonWebTokenError) {
      const status = HttpStatus.UNAUTHORIZED;

      const responseBody = {
        statusCode: status,
        message: UnauthorizedMessage.INVALID_TOKEN,
        code: UnauthorizedCode.INVALID_TOKEN,
        timestamp: new Date().toISOString(),
        path: ctx.getRequest().url
      };

      response.status(status).send(responseBody);
      return;
    }

    let status =
      exception instanceof HttpException
      ? exception.getStatus()
      : HttpStatus.INTERNAL_SERVER_ERROR;

    let message =
      exception instanceof HttpException
      ? exception.getResponse()
      : InternalServerErrorMessage.INTERNAL_SERVER_ERROR;

    if (typeof message === 'object' && (message as any).message) {
      message = (message as any).message;
    }

    response.status(status).send({
      success: false,
      timestamp: new Date().toISOString(),
      path: request.url,
      statusCode: status,
      message: message,
      error: InternalServerErrorCode
    });
  }
}