/**
 * Script pour créer un booking de test avec statut PENDING
 * Usage: node create-test-booking.js
 */

const { Client } = require('pg');
const { v4: uuidv4 } = require('uuid');

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

  try {
    await client.connect();
    console.log('✅ Connecté à la base de données');

    const bookingId = uuidv4();
    const confirmationToken = uuidv4();
    const userId = '8cf7d5b3-d94f-44aa-bb5a-080002919dd1'; // User demo@xpeditis.com
    const organizationId = '199fafa9-d26f-4cf9-9206-73432baa8f63';

    // Create dummy documents in JSONB format
    const dummyDocuments = JSON.stringify([
      {
        id: uuidv4(),
        type: 'BILL_OF_LADING',
        fileName: 'bill-of-lading.pdf',
        filePath: 'https://dummy-storage.com/documents/bill-of-lading.pdf',
        mimeType: 'application/pdf',
        size: 102400, // 100KB
        uploadedAt: new Date().toISOString(),
      },
      {
        id: uuidv4(),
        type: 'PACKING_LIST',
        fileName: 'packing-list.pdf',
        filePath: 'https://dummy-storage.com/documents/packing-list.pdf',
        mimeType: 'application/pdf',
        size: 51200, // 50KB
        uploadedAt: new Date().toISOString(),
      },
      {
        id: uuidv4(),
        type: 'COMMERCIAL_INVOICE',
        fileName: 'commercial-invoice.pdf',
        filePath: 'https://dummy-storage.com/documents/commercial-invoice.pdf',
        mimeType: 'application/pdf',
        size: 76800, // 75KB
        uploadedAt: new Date().toISOString(),
      },
    ]);

    const query = `
      INSERT INTO csv_bookings (
        id, user_id, organization_id, carrier_name, carrier_email,
        origin, destination, volume_cbm, weight_kg, pallet_count,
        price_usd, price_eur, primary_currency, transit_days, container_type,
        status, confirmation_token, requested_at, notes, documents
      ) VALUES (
        $1, $2, $3, $4, $5, $6, $7, $8, $9, $10,
        $11, $12, $13, $14, $15, $16, $17, NOW(), $18, $19
      ) RETURNING id, confirmation_token;
    `;

    const values = [
      bookingId,
      userId,
      organizationId,
      'Test Carrier',
      'test@carrier.com',
      'NLRTM', // Rotterdam
      'USNYC', // New York
      25.5, // volume_cbm
      3500, // weight_kg
      10, // pallet_count
      1850.5, // price_usd
      1665.45, // price_eur
      'USD', // primary_currency
      28, // transit_days
      'LCL', // container_type
      'PENDING', // status - IMPORTANT!
      confirmationToken,
      'Test booking created by script',
      dummyDocuments, // documents JSONB
    ];

    const result = await client.query(query, values);

    console.log('\n🎉 Booking de test créé avec succès!');
    console.log('━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━');
    console.log(`📦 Booking ID: ${bookingId}`);
    console.log(`🔑 Token: ${confirmationToken}`);
    console.log('━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━\n');
    console.log('🔗 URLs de test:');
    console.log(`   Accept:  http://localhost:3000/carrier/accept/${confirmationToken}`);
    console.log(`   Reject:  http://localhost:3000/carrier/reject/${confirmationToken}`);
    console.log('\n📧 URL API (pour curl):');
    console.log(`   curl http://localhost:4000/api/v1/csv-bookings/accept/${confirmationToken}`);
    console.log('\n✅ Ce booking est en statut PENDING et peut être accepté/refusé.\n');
  } catch (error) {
    console.error('❌ Erreur:', error.message);
    console.error(error);
  } finally {
    await client.end();
  }
}

createTestBooking();
