#!/usr/bin/env node
/**
 * Inspect what upstream EasyGDS actually returns for a given booking's
 * Contact tab data, so we can verify the booking-details page is showing
 * the right thing (or find missing/mismapped fields).
 *
 * Usage:
 *   node server/scripts/inspect-booking-contact.cjs DEMOS202302255
 */

const fs = require('fs');
const path = require('path');

// Load .env (project root)
const envPath = path.join(__dirname, '..', '..', '.env');
if (fs.existsSync(envPath)) {
  for (const line of fs.readFileSync(envPath, 'utf-8').split('\n')) {
    const m = line.match(/^\s*([A-Z_]+)\s*=\s*"?([^"\n]*?)"?\s*$/);
    if (m && !process.env[m[1]]) process.env[m[1]] = m[2];
  }
}

const EASYGDS_IAM_URL = process.env.EASYGDS_IAM_URL || 'https://iam.stg-services.easygds.com/api';
const EASYGDS_CORE_URL = process.env.EASYGDS_CORE_URL || 'https://core.stg-services.easygds.com/api';
const EASYGDS_EMAIL = process.env.EASYGDS_EMAIL || 'crm@serviceaccount.easygds.com';
const EASYGDS_PASSWORD = process.env.EASYGDS_PASSWORD || 'm27qwe9';

const code = process.argv[2] || 'DEMOS202302255';

async function getToken() {
  const res = await fetch(`${EASYGDS_IAM_URL}/auth`, {
    method: 'POST',
    headers: { 'Content-Type': 'application/json' },
    body: JSON.stringify({
      scope_type: 'System', scope_id: '',
      email: EASYGDS_EMAIL, secret_key: EASYGDS_PASSWORD,
      flow_type: 'Basic',
    }),
  });
  const data = await res.json();
  if (!data.access_token) throw new Error(data.message || 'Auth failed');
  return data.access_token;
}

async function call(token, endpoint) {
  const res = await fetch(`${EASYGDS_CORE_URL}${endpoint}`, {
    headers: { Authorization: `Bearer ${token}`, 'Content-Type': 'application/json' },
  });
  return res.json();
}

(async () => {
  console.log(`→ Looking up booking by code: ${code}`);
  const token = await getToken();

  // 1. Find booking by code
  const list = await call(token, `/bookings/list?per_page=5&search_text=${encodeURIComponent(code)}`);
  const match = (list.result || []).find(b => b.code === code) || (list.result || [])[0];
  if (!match) {
    console.error(`✗ Booking ${code} not found`);
    console.log('list response:', JSON.stringify(list, null, 2));
    process.exit(1);
  }
  console.log(`✓ Found booking_id: ${match.id}`);
  console.log(`  app: ${match.app?.name || '(none)'}, agent_id: ${match.agent_id || '(none)'}, language_code: ${match.language_code || '(none)'}`);
  console.log(`  has b.contact?: ${!!match.contact}`);
  if (match.contact) console.log('  embedded contact:', JSON.stringify(match.contact, null, 2));

  // 2. Fetch dedicated contact endpoint
  const contact = await call(token, `/bookings/contact?booking_id=${match.id}`);
  console.log('\n────── /bookings/contact?booking_id ──────');
  console.log(JSON.stringify(contact, null, 2));

  // 3. Fetch travelers as a fallback signal (often has contact-like fields too)
  const travelers = await call(token, `/bookings/travelers?booking_id=${match.id}`);
  console.log('\n────── /bookings/travelers?booking_id ──────');
  console.log(JSON.stringify(travelers, null, 2));

  // 4. Summarize what the UI would show — apply the same unwrap as the server fix
  const c = contact?.contact || contact?.result || contact || {};
  console.log('\n────── What the booking-details Contact tab would render ──────');
  console.log(`  Direct partner →`);
  console.log(`     Buyer group: ${c.country_code || c.country || (match.language_code || '').toUpperCase() || '-'}`);
  console.log(`     Name:        ${match.app?.name || '-'}`);
  console.log(`     E-mail:      ${c.email || '-'}`);
  console.log(`     Phone:       ${c.phone || '-'}`);
  console.log(`  Booking agent → User data →`);
  console.log(`     Name:        ${[c.title, c.first_name, c.last_name].filter(Boolean).join(' ') || '-'}`);
  console.log(`     E-mail:      ${c.email || '-'}`);
  console.log(`     Phone:       ${c.phone || '-'}`);
  console.log(`  Contact information →`);
  console.log(`     Name:        ${[c.title, c.first_name, c.last_name].filter(Boolean).join(' ') || '-'}`);
  console.log(`     E-mail:      ${c.email || '-'}`);
  console.log(`     Phone:       ${c.phone || '-'}`);
  console.log(`     Country:     ${c.country || c.country_code || c.city || '-'}`);
})().catch(e => {
  console.error('✗ Fatal:', e.message);
  process.exit(1);
});
