/**
 * Script to fix dummy storage URLs in the database
 *
 * This script updates all document URLs from "dummy-storage.com" to proper MinIO URLs
 */

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

const MINIO_ENDPOINT = process.env.AWS_S3_ENDPOINT || 'http://localhost:9000';
const BUCKET_NAME = 'xpeditis-documents';

async function fixDummyUrls() {
  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');

    // Get all CSV bookings with documents
    const result = await client.query(
      `SELECT id, documents FROM csv_bookings WHERE documents IS NOT NULL AND documents::text LIKE '%dummy-storage%'`
    );

    console.log(`\n📄 Found ${result.rows.length} bookings with dummy URLs\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('dummy-storage')) {
          // Extract filename from dummy URL
          const fileName = doc.fileName || doc.filePath.split('/').pop();
          const documentId = doc.id;

          // Build proper MinIO URL
          const newUrl = `${MINIO_ENDPOINT}/${BUCKET_NAME}/csv-bookings/${bookingId}/${documentId}-${fileName}`;

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

          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`);
    console.log(`\n⚠️  Note: The actual files need to be uploaded to MinIO at the correct paths.`);
    console.log(`   You can upload test files or re-create the bookings with real file uploads.`);
  } catch (error) {
    console.error('❌ Error:', error);
    throw error;
  } finally {
    await client.end();
    console.log('\n👋 Disconnected from database');
  }
}

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