/**
 * Script to fix minio hostname in document URLs
 *
 * Changes http://minio:9000 to http://localhost:9000
 */

const { Client } = require('pg');
require('dotenv').config();

async function fixMinioHostname() {
  const client = new Client({
    host: process.env.DATABASE_HOST || 'localhost',
    port: process.env.DATABASE_PORT || 5432,
    user: process.env.DATABASE_USER || 'xpeditis',
    password: process.env.DATABASE_PASSWORD || 'xpeditis_dev_password',
    database: process.env.DATABASE_NAME || 'xpeditis_dev',
  });

  try {
    await client.connect();
    console.log('✅ Connected to database');

    // Find bookings with minio:9000 in URLs
    const result = await client.query(
      `SELECT id, documents FROM csv_bookings WHERE documents::text LIKE '%http://minio:9000%'`
    );

    console.log(`\n📄 Found ${result.rows.length} bookings with minio hostname\n`);

    let updatedCount = 0;

    for (const row of result.rows) {
      const bookingId = row.id;
      const documents = row.documents;

      // Update each document URL
      const updatedDocuments = documents.map(doc => {
        if (doc.filePath && doc.filePath.includes('http://minio:9000')) {
          const newUrl = doc.filePath.replace('http://minio:9000', 'http://localhost:9000');

          console.log(`   Booking: ${bookingId}`);
          console.log(`   Old: ${doc.filePath}`);
          console.log(`   New: ${newUrl}\n`);

          return {
            ...doc,
            filePath: newUrl,
          };
        }
        return doc;
      });

      // Update the database
      await client.query(`UPDATE csv_bookings SET documents = $1 WHERE id = $2`, [
        JSON.stringify(updatedDocuments),
        bookingId,
      ]);

      updatedCount++;
      console.log(`✅ Updated booking ${bookingId}\n`);
    }

    console.log(`\n🎉 Successfully updated ${updatedCount} bookings`);
  } catch (error) {
    console.error('❌ Error:', error);
    throw error;
  } finally {
    await client.end();
    console.log('\n👋 Disconnected from database');
  }
}

fixMinioHostname()
  .then(() => {
    console.log('\n✅ Script completed successfully');
    process.exit(0);
  })
  .catch(error => {
    console.error('\n❌ Script failed:', error);
    process.exit(1);
  });
