/**
 * @ai-summary Vehicle catalog data seeding service
 * @ai-context Loads vehicle catalog data from exported SQL files after migrations
 */

import { Pool } from 'pg';
import { logger } from '../../../core/logging/logger';
import * as fs from 'fs';
import * as path from 'path';

export class CatalogSeedService {
  private readonly dataDir = '/app/migrations/features/platform/data';

  constructor(private pool: Pool) {}

  /**
   * Seed vehicle catalog data if tables are empty
   */
  async seedIfEmpty(): Promise<void> {
    try {
      // Check if data already exists
      const count = await this.pool.query('SELECT COUNT(*) FROM vehicle_options');
      const rowCount = parseInt(count.rows[0].count, 10);

      if (rowCount > 0) {
        logger.info('Vehicle catalog already seeded, skipping', { rowCount });
        return;
      }

      logger.info('Seeding vehicle catalog data...');

      // Load data files in order
      await this.loadDataFile('engines.sql');
      await this.loadDataFile('transmissions.sql');
      await this.loadDataFile('vehicle_options.sql');

      // Verify data loaded
      const finalCount = await this.pool.query('SELECT COUNT(*) FROM vehicle_options');
      const finalRowCount = parseInt(finalCount.rows[0].count, 10);

      logger.info('Vehicle catalog seeding complete', { rowCount: finalRowCount });
    } catch (error: any) {
      logger.error('Failed to seed vehicle catalog', { error: error.message });
      throw error;
    }
  }

  /**
   * Load and execute a SQL data file
   */
  private async loadDataFile(filename: string): Promise<void> {
    const filePath = path.join(this.dataDir, filename);

    // Check if file exists
    if (!fs.existsSync(filePath)) {
      logger.warn('Data file not found, skipping', { filePath });
      return;
    }

    logger.info('Loading data file', { filename });

    try {
      // Read SQL file
      const sql = fs.readFileSync(filePath, 'utf-8');

      // Execute SQL (pg library handles INSERT statements properly)
      await this.pool.query(sql);

      logger.info('Data file loaded successfully', { filename });
    } catch (error: any) {
      logger.error('Failed to load data file', { filename, error: error.message });
      throw error;
    }
  }
}
