import { ExceptionFilter, Catch, ArgumentsHost, HttpException, HttpStatus } from '@nestjs/common';
import { Response } from 'express';
import { DeleteOperationException } from './delete-operation.exception';

@Catch(DeleteOperationException, HttpException)
export class DeleteExceptionFilter implements ExceptionFilter {
  catch(exception: DeleteOperationException | HttpException, host: ArgumentsHost) {
    const ctx = host.switchToHttp();
    const response = ctx.getResponse<Response>();
    const status = exception.getStatus?.() || HttpStatus.BAD_REQUEST;

    if (exception instanceof DeleteOperationException) {
      // Format the response specifically for delete operations
      response.status(status).json({
        statusCode: status,
        error: 'Delete Operation Failed',
        message: exception.message,
        timestamp: new Date().toISOString(),
        type: 'DELETE_CONSTRAINT_VIOLATION',
        userFriendly: true,
        details: {
          canRetry: true,
          action: 'RESOLVE_DEPENDENCIES',
          hint: 'Please resolve the listed dependencies and try again.'
        }
      });
    } else if (exception instanceof HttpException) {
      // Handle other HTTP exceptions normally
      const exceptionResponse = exception.getResponse();
      
      response.status(status).json({
        statusCode: status,
        timestamp: new Date().toISOString(),
        ...(typeof exceptionResponse === 'object' 
          ? exceptionResponse 
          : { message: exceptionResponse }
        )
      });
    }
  }
}