/**
 * Drift Detection Service
 *
 * Previously monitored data drift between Prisma and Supabase databases.
 * Now a no-op stub since Supabase has been removed — Convex (via Prisma adapter) is the
 * single source of truth.
 *
 * Exported types and singleton are preserved so existing job handlers compile.
 */

import { logger } from '../logger';

// ============================================================================
// Types (preserved for API compatibility)
// ============================================================================

export interface TableDriftReport {
  tableName: string;
  prismaCount: number;
  supabaseCount: number;
  countDifference: number;
  driftPercentage: number;
  missingInSupabase: string[];
  orphanedInSupabase: string[];
  exceedsThreshold: boolean;
  oldestMissingRecordDate: string | null;
  newestMissingRecordDate: string | null;
}

export interface DriftReport {
  generatedAt: string;
  status: 'healthy' | 'warning' | 'critical';
  summary: {
    totalTablesChecked: number;
    tablesWithDrift: number;
    totalMissingRecords: number;
    totalOrphanedRecords: number;
    highestDriftPercentage: number;
  };
  tables: TableDriftReport[];
  configuration: DriftDetectionConfig;
  durationMs: number;
}

export interface DriftDetectionConfig {
  countThreshold: number;
  percentageThreshold: number;
  maxIdsToCheck: number;
  tablesToMonitor: MonitoredTable[];
}

export interface MonitoredTable {
  name: string;
  prismaIdColumn: string;
  supabaseIdColumn: string;
  prismaTimestampColumn: string;
  supabaseTimestampColumn: string;
}

// ============================================================================
// Configuration
// ============================================================================

const DEFAULT_CONFIG: DriftDetectionConfig = {
  countThreshold: 10,
  percentageThreshold: 1,
  maxIdsToCheck: 1000,
  tablesToMonitor: [],
};

// ============================================================================
// Drift Detection Service (no-op — Supabase removed)
// ============================================================================

export class DriftDetectionService {
  private config: DriftDetectionConfig;
  private scopedLogger = logger.scope('DriftDetection');

  constructor(config?: Partial<DriftDetectionConfig>) {
    this.config = {
      ...DEFAULT_CONFIG,
      ...config,
      tablesToMonitor: config?.tablesToMonitor || DEFAULT_CONFIG.tablesToMonitor,
    };
  }

  /**
   * Run drift detection — no-op since Supabase was removed.
   * Returns a healthy report with zero drift.
   */
  async runDriftCheck(): Promise<DriftReport> {
    this.scopedLogger.info(
      'Drift detection skipped — Supabase removed, single-database architecture'
    );

    return {
      generatedAt: new Date().toISOString(),
      status: 'healthy',
      summary: {
        totalTablesChecked: 0,
        tablesWithDrift: 0,
        totalMissingRecords: 0,
        totalOrphanedRecords: 0,
        highestDriftPercentage: 0,
      },
      tables: [],
      configuration: this.config,
      durationMs: 0,
    };
  }

  /**
   * Update configuration (retained for API compatibility)
   */
  updateConfig(config: Partial<DriftDetectionConfig>): void {
    this.config = {
      ...this.config,
      ...config,
      tablesToMonitor: config.tablesToMonitor || this.config.tablesToMonitor,
    };
  }

  /**
   * Get current configuration
   */
  getConfig(): DriftDetectionConfig {
    return { ...this.config };
  }
}

// ============================================================================
// Singleton Export
// ============================================================================

export const driftDetectionService = new DriftDetectionService();

// Re-export types for convenience
export type { DriftDetectionConfig as DriftConfig };
