import { BadRequestException } from '@nestjs/common';

export interface DeleteConstraint {
  entityName: string;
  count: number;
  action: 'delete' | 'reassign' | 'cancel' | 'complete';
}

export class DeleteOperationException extends BadRequestException {
  constructor(
    entityType: string,
    entityName: string,
    constraints: DeleteConstraint[]
  ) {
    const message = DeleteOperationException.buildUserFriendlyMessage(
      entityType,
      entityName,
      constraints
    );
    super(message);
  }

  private static buildUserFriendlyMessage(
    entityType: string,
    entityName: string,
    constraints: DeleteConstraint[]
  ): string {
    const baseMessage = `Cannot delete ${entityType.toLowerCase()} "${entityName}".`;
    
    if (constraints.length === 0) {
      return `${baseMessage} Unknown constraint violation.`;
    }

    const constraintMessages = constraints.map(constraint => {
      const { entityName: constraintEntity, count, action } = constraint;
      
      const entityDisplayName = count === 1 
        ? constraintEntity.toLowerCase()
        : `${constraintEntity.toLowerCase()}s`;
      
      const actionText = this.getActionText(action, count);
      
      return `• ${count} ${entityDisplayName} ${count === 1 ? 'is' : 'are'} still ${this.getStatusText(constraintEntity)}. Please ${actionText} first.`;
    });

    return [
      baseMessage,
      '',
      'The following dependencies must be resolved:',
      ...constraintMessages,
      '',
      'Once all dependencies are resolved, you can retry the deletion.'
    ].join('\n');
  }

  private static getActionText(action: string, count: number): string {
    const actions: Record<string, string> = {
      delete: count === 1 ? 'delete it' : 'delete them',
      reassign: count === 1 ? 'reassign it' : 'reassign them',
      cancel: count === 1 ? 'cancel it' : 'cancel them',
      complete: count === 1 ? 'complete it' : 'complete them'
    };
    return actions[action] || (count === 1 ? 'resolve it' : 'resolve them');
  }

  private static getStatusText(entityName: string): string {
    const statusTexts: Record<string, string> = {
      booking: 'active',
      schedule: 'in use',
      coach: 'assigned',
      seat: 'occupied or blocked',
      'seat class': 'in use by fare rules',
      'coach type': 'in use by coaches or seat classes',
      train: 'scheduled',
      ticket: 'issued',
      'payment record': 'linked',
      'fare rule': 'active',
      route: 'in use by schedules',
      passenger: 'active with bookings or accounts',
      promotion: 'active',
      station: 'in use by routes'
    };
    return statusTexts[entityName.toLowerCase()] || 'in use';
  }
}