import { config } from 'dotenv';
import { neon } from '@neondatabase/serverless';
import * as fs from 'fs';

// Load .env.local
config({ path: '.env.local' });

const SOURCE_SITE_ID = process.env.SITE_ID || process.env.RANKTRACTION_SITE_ID;
const DATABASE_URL = process.env.DATABASE_URL;

if (!SOURCE_SITE_ID || !DATABASE_URL) {
  console.error('Missing SITE_ID or DATABASE_URL in .env.local');
  process.exit(1);
}

const sql = neon(DATABASE_URL);

async function main() {
  console.log(`Connecting to database to export CMS data for site prefix: ${SOURCE_SITE_ID}...`);
  try {
    // Select all rows where site_id starts with the current site ID (e.g. 'ten-sura-game.com' or 'ten-sura-game.com-about-us')
    const rows = await sql`SELECT * FROM homepage_content WHERE site_id LIKE ${SOURCE_SITE_ID + '%'}`;
    
    fs.writeFileSync('cms-seed-data.json', JSON.stringify(rows, null, 2));
    console.log(`Successfully exported ${rows.length} CMS rows to cms-seed-data.json.`);
  } catch (error) {
    console.error('Error exporting CMS data:', error);
  }
}

main();
