#!/usr/bin/env node

/**
 * Prisma → Supabase Data Sync Script (Refactored)
 *
 * This script synchronizes all data from Prisma PostgreSQL to Supabase PostgreSQL.
 * It uses the modular database-sync library for maintainability.
 *
 * Usage:
 *   node scripts/sync-prisma-to-supabase.mjs [options]
 *
 * Options:
 *   --tables=users,contacts    Sync specific tables only
 *   --skip-empty              Skip tables with no data
 *   --quiet                   Minimal output
 *   --help                    Show help
 *
 * Examples:
 *   node scripts/sync-prisma-to-supabase.mjs
 *   node scripts/sync-prisma-to-supabase.mjs --tables=users
 *   node scripts/sync-prisma-to-supabase.mjs --quiet
 *
 * @see lib/database-sync for implementation details
 */

import { syncAllTables, SyncEngine } from '../lib/database-sync/sync-engine.ts';
import { getSyncableTables } from '../lib/database-sync/config.ts';

/**
 * Parse command line arguments
 */
function parseArgs() {
  const args = process.argv.slice(2);

  const options = {
    tables: undefined as string[] | undefined,
    skipEmpty: true,
    verbose: true,
    showHelp: false,
  };

  for (const arg of args) {
    if (arg === '--help' || arg === '-h') {
      options.showHelp = true;
    } else if (arg.startsWith('--tables=')) {
      options.tables = arg.split('=')[1].split(',');
    } else if (arg === '--skip-empty') {
      options.skipEmpty = true;
    } else if (arg === '--quiet' || arg === '-q') {
      options.verbose = false;
    }
  }

  return options;
}

/**
 * Show help message
 */
function showHelp() {
  console.log(`
╔═══════════════════════════════════════════════════════════════╗
║  Prisma → Supabase Data Sync                                  ║
╚═══════════════════════════════════════════════════════════════╝

Synchronizes all data from Prisma to Supabase with automatic
field mapping, error recovery, and progress reporting.

USAGE:
  node scripts/sync-prisma-to-supabase.mjs [options]

OPTIONS:
  --tables=TABLE1,TABLE2    Sync specific tables only
  --skip-empty             Skip tables with no data (default)
  --quiet, -q              Minimal output
  --help, -h               Show this help message

EXAMPLES:
  # Sync all tables
  node scripts/sync-prisma-to-supabase.mjs

  # Sync only users and contacts
  node scripts/sync-prisma-to-supabase.mjs --tables=users,contacts

  # Quiet mode
  node scripts/sync-prisma-to-supabase.mjs --quiet

TABLES THAT WILL BE SYNCED:
${getSyncableTables()
  .map((t) => `  • ${t.name.padEnd(25)} (${t.description})`)
  .join('\n')}

REQUIREMENTS:
  • Supabase must be running (npm run supabase:start)
  • Environment variables must be set (.env.local)
  • All tables must exist in Supabase

TROUBLESHOOTING:
  • Missing tables: npm run supabase:init-tables
  • Missing columns: Run migration files in supabase/migrations/
  • Connection error: Check Supabase is running on port 54322

DOCUMENTATION:
  • Full guide: SUPABASE_SYNC_COMPLETE.md
  • Prevention: DATABASE_SYNC_PREVENTION.md
  • Architecture: DUAL_DATABASE_ARCHITECTURE.md

╚═══════════════════════════════════════════════════════════════╝
`);
}

/**
 * Main execution function
 */
async function main() {
  const options = parseArgs();

  // Show help if requested
  if (options.showHelp) {
    showHelp();
    process.exit(0);
  }

  // Load environment variables
  const dotenv = await import('dotenv');
  dotenv.config({ path: '.env.local' });

  // Verify environment variables
  if (!process.env.NEXT_PUBLIC_SUPABASE_URL || !process.env.SUPABASE_SERVICE_ROLE_KEY) {
    console.error('❌ Missing required environment variables:');
    console.error('   NEXT_PUBLIC_SUPABASE_URL');
    console.error('   SUPABASE_SERVICE_ROLE_KEY');
    console.error('');
    console.error('   Check .env.local file');
    process.exit(1);
  }

  // Run sync
  const engine = new SyncEngine();

  try {
    const result = await engine.syncAll({
      tables: options.tables,
      skipEmpty: options.skipEmpty,
      verbose: options.verbose,
      continueOnError: true,
    });

    // Exit with appropriate code
    if (result.success) {
      process.exit(0);
    } else {
      if (result.totalErrors <= 5) {
        // Minor errors, don't block
        console.log('⚠️  Completed with minor errors (non-blocking)');
        process.exit(0);
      } else {
        // Too many errors, block
        console.error('❌ Sync failed with too many errors');
        process.exit(1);
      }
    }
  } catch (error) {
    console.error('❌ Fatal error during sync:', error);
    process.exit(1);
  } finally {
    await engine.disconnect();
  }
}

// Run if called directly
if (import.meta.url === `file://${process.argv[1]}`) {
  main().catch((error) => {
    console.error('❌ Unhandled error:', error);
    process.exit(1);
  });
}

export { main };
