/**
 * @ai-summary Generates combined schema from all feature migrations
 */
import { readFileSync, readdirSync, writeFileSync } from 'fs';
import { join } from 'path';

const FEATURES_DIR = join(__dirname, '../../features');
const OUTPUT_FILE = join(__dirname, 'combined-schema.sql');

function collectFeatureMigrations(): string[] {
  const schemas: string[] = [];
  
  const features = readdirSync(FEATURES_DIR);
  
  for (const feature of features) {
    const migrationDir = join(FEATURES_DIR, feature, 'migrations');
    
    try {
      const files = readdirSync(migrationDir)
        .filter(f => f.endsWith('.sql'))
        .sort();
      
      schemas.push(`-- =====================================`);
      schemas.push(`-- Feature: ${feature}`);
      schemas.push(`-- =====================================\n`);
      
      for (const file of files) {
        const content = readFileSync(join(migrationDir, file), 'utf-8');
        schemas.push(`-- File: ${file}`);
        schemas.push(content);
        schemas.push('');
      }
    } catch (error) {
      console.warn(`No migrations found for ${feature}`);
    }
  }
  
  return schemas;
}

function main() {
  console.log('Generating combined schema...');
  
  const header = `-- MotoVaultPro Combined Schema
-- Generated: ${new Date().toISOString()}
-- This file is auto-generated from feature migrations
-- DO NOT EDIT DIRECTLY

`;
  
  const schemas = collectFeatureMigrations();
  const combined = header + schemas.join('\n');
  
  writeFileSync(OUTPUT_FILE, combined);
  console.log(`✅ Schema generated: ${OUTPUT_FILE}`);
}

if (require.main === module) {
  main();
}