import type { IServiceContainer } from '@stock-bot/handlers';
import { getLogger } from '@stock-bot/logger';
import type { JobPayload } from '../../../types/job-payloads';

const logger = getLogger('enhanced-sync-provider-mapping-stats');

interface ProviderMappingStats {
  provider: string;
  total_mappings: string;
  active_mappings: string;
  verified_mappings: string;
  auto_mapped: string;
  avg_confidence: string;
}

export async function getProviderMappingStats(
  payload: JobPayload,
  container: IServiceContainer
): Promise<ProviderMappingStats[]> {
  logger.info('Getting provider mapping statistics...');

  try {
    const postgresClient = container.postgres;
    const query = `
      SELECT 
        provider,
        COUNT(*) as total_mappings,
        COUNT(CASE WHEN active = true THEN 1 END) as active_mappings,
        COUNT(CASE WHEN verified = true THEN 1 END) as verified_mappings,
        COUNT(CASE WHEN auto_mapped = true THEN 1 END) as auto_mapped,
        AVG(confidence) as avg_confidence
      FROM provider_exchange_mappings
      GROUP BY provider
      ORDER BY provider
    `;
    const result = await postgresClient.query(query);

    logger.info('Retrieved provider mapping statistics');
    return result.rows;
  } catch (error) {
    logger.error('Failed to get provider mapping statistics', { error });
    throw error;
  }
}
