import { HttpStatus } from '@nestjs/common';
import { BusinessException } from '@common/exceptions/business.exception';

export class AzureCredentialMissingException extends BusinessException {
  constructor(missing: string[]) {
    super(
      `M365 sync credentials missing in .env: ${missing.join(', ')}`,
      'AZURE_CREDENTIAL_MISSING',
      HttpStatus.BAD_REQUEST,
      { missing },
    );
  }
}

export class GraphInsufficientScopeException extends BusinessException {
  constructor(detail?: string) {
    super(
      'Azure App Registration missing scope (AuditLog.Read.All or Reports.Read.All). Add and admin-consent in Azure Portal.',
      'GRAPH_INSUFFICIENT_SCOPE',
      HttpStatus.BAD_GATEWAY,
      { detail },
    );
  }
}

export class GraphAuthFailedException extends BusinessException {
  constructor(detail?: string) {
    super('Failed to acquire Graph access token', 'GRAPH_AUTH_FAILED', HttpStatus.BAD_GATEWAY, { detail });
  }
}

export class GraphRateLimitException extends BusinessException {
  constructor(detail?: string) {
    super('Microsoft Graph rate-limited after retries', 'GRAPH_RATE_LIMIT', HttpStatus.BAD_GATEWAY, { detail });
  }
}

export class GraphUpstreamErrorException extends BusinessException {
  constructor(detail?: string) {
    super('Microsoft Graph upstream error', 'GRAPH_UPSTREAM_ERROR', HttpStatus.BAD_GATEWAY, { detail });
  }
}

export class ReportsObfuscatedException extends BusinessException {
  constructor() {
    super(
      'M365 activity report UPNs are obfuscated. In M365 Admin Center → Settings → Org settings → Services → Reports, uncheck "Display concealed user, group, and site names in all reports".',
      'REPORTS_OBFUSCATED',
      HttpStatus.BAD_GATEWAY,
    );
  }
}

export class SyncInProgressException extends BusinessException {
  constructor(executionId: string) {
    super('A sync is already running. Wait for it to finish.', 'SYNC_IN_PROGRESS', HttpStatus.CONFLICT, {
      executionId,
    });
  }
}

export class NoSuccessfulSyncException extends BusinessException {
  constructor() {
    super('No successful sync yet. Trigger a sync first.', 'NO_SUCCESSFUL_SYNC', HttpStatus.NOT_FOUND);
  }
}

export class M365UserNotFoundException extends BusinessException {
  constructor(userId: string) {
    super('M365 user not found', 'USER_NOT_FOUND', HttpStatus.NOT_FOUND, { userId });
  }
}

export class ExportTooLargeException extends BusinessException {
  constructor(rowCount: number, limit: number) {
    super(
      `Export would produce ${rowCount} rows, exceeding the ${limit}-row limit. Narrow the filter.`,
      'EXPORT_TOO_LARGE',
      HttpStatus.BAD_REQUEST,
      { rowCount, limit },
    );
  }
}
