import {
  ExceptionFilter,
  Catch,
  ArgumentsHost,
  HttpException,
  HttpStatus
} from '@nestjs/common';
import { JsonWebTokenError, TokenExpiredError } from '@nestjs/jwt';
import { FastifyReply, FastifyRequest } from 'fastify';

@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: 'Access Token Expired',
        code: 'AccessTokenExpired',
        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: 'Invalid Token',
        code: 'InvalidToken',
        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()
      : '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,
      error: message
    });
  }
}