import { ArgumentsHost, Catch, ExceptionFilter, UnauthorizedException } from '@nestjs/common';
import { error_message } from 'src/common/error_message';
import { LoggerService } from 'src/common/logger/logger.service';
const pjson = require('../../package.json');

@Catch(UnauthorizedException)
export class UnauthorizedInterceptor implements ExceptionFilter {
    constructor(
        private readonly logger: LoggerService
    ) {}
        
  catch(exception: UnauthorizedException, host: ArgumentsHost) {
    const response = host.switchToHttp().getResponse();
    const message = error_message.unauthorized;
    const exceptionResponse = exception.getResponse() as any;

    this.logger.responseOut({
        error: true,
        statusCode: 401,
        message: error_message.unauthorized
    })

    response.status(401).json({
      error: {
        code: 401,
        title: "Unauthorized",
        message: (exception.getResponse() as any).message,
      },
      data: {},
      meta: {
        version: pjson['version']
      }
    });
  }
}