/**
 * @ai-summary Scheduled cache cleanup job for stations
 */

import { Pool } from 'pg';
import { logger } from '../../../core/logging/logger';

/**
 * Clean up expired station cache entries
 * Runs daily at 2 AM
 * Deletes entries older than 24 hours
 */
export async function cleanupStationCache(pool: Pool): Promise<void> {
  const startTime = Date.now();

  try {
    logger.info('Starting station cache cleanup job');

    // Calculate timestamp for entries older than 24 hours
    const cutoffTime = new Date(Date.now() - 24 * 60 * 60 * 1000);

    // Execute cleanup query
    const result = await pool.query(
      `DELETE FROM station_cache
       WHERE created_at < $1
       RETURNING id`,
      [cutoffTime]
    );

    const deletedCount = result.rowCount || 0;
    const duration = Date.now() - startTime;

    logger.info('Station cache cleanup completed', {
      deletedCount,
      durationMs: duration,
      cutoffTime: cutoffTime.toISOString()
    });

    // Log warning if cleanup took longer than expected
    if (duration > 5000) {
      logger.warn('Station cache cleanup took longer than expected', {
        durationMs: duration
      });
    }
  } catch (error) {
    logger.error('Station cache cleanup failed', {
      error: error instanceof Error ? error.message : String(error),
      durationMs: Date.now() - startTime
    });

    // Re-throw to let scheduler handle failure
    throw error;
  }
}

/**
 * Get cache statistics for monitoring
 */
export async function getCacheStats(pool: Pool): Promise<{
  totalEntries: number;
  oldestEntry: Date | null;
  newestEntry: Date | null;
}> {
  const result = await pool.query(
    `SELECT
      COUNT(*) as total,
      MIN(created_at) as oldest,
      MAX(created_at) as newest
     FROM station_cache`
  );

  const row = result.rows[0];

  return {
    totalEntries: parseInt(row.total, 10),
    oldestEntry: row.oldest ? new Date(row.oldest) : null,
    newestEntry: row.newest ? new Date(row.newest) : null
  };
}
