// src/config/travelport.js
// Centralised config — credentials loaded from .env
// Bearer token is NOT stored here; it is fetched dynamically by authService.js
require('dotenv').config();
const fs   = require('fs');
const path = require('path');

// ── Debug logger ──────────────────────────────────────────────────────────────
const saveDebugLog = (fileName, data) => {
  try {
    const debugDir = path.resolve(__dirname, '../debug-xml');
    if (!fs.existsSync(debugDir)) fs.mkdirSync(debugDir, { recursive: true });
    fs.writeFileSync(path.join(debugDir, fileName), JSON.stringify(data, null, 2));
  } catch (err) {
    console.error(`Debug save error: ${err.message}`);
  }
};
// ─────────────────────────────────────────────────────────────────────────────

const travelportConfig = {
  get baseUrl() {
    const env = process.env.TRAVELPORT_ENV || 'preProduction';
    return env === 'production'
      ? 'https://api.travelport.net/11'
      : 'https://api.pp.travelport.net/11';
  },
  accessGroup:    process.env.TRAVELPORT_ACCESS_GROUP,
  sessionId:      process.env.TRAVELPORT_SESSION_ID,
  pccCore:        process.env.TRAVELPORT_PCC_CORE,
  traceIdPrefix:  'BOBROS-',

  endpoints: {
    lowFareSearch: '/air/catalog/search/catalogproductofferings',
  },

  generateTraceId() {
    return `${this.traceIdPrefix}${Date.now()}`;
  },

  /**
   * Build Travelport request headers.
   * @param {string} bearerToken  - obtained from authService.getBearerToken()
   */
  buildHeaders(bearerToken) {
    const headers = {
    'Content-Type':    'application/json',
     'Accept': 'application/json',
      'Accept-Encoding': 'gzip, deflate',
      'Cache-Control': 'no-cache',
      'Accept-Version': '11',
      'Content-Version': '11',
       XAUTH_TRAVELPORT_ACCESSGROUP: this.accessGroup,
      'username':                       process.env.TRAVELPORT_USERNAME_JSON,
      'password':                       process.env.TRAVELPORT_PASSWORD_JSON,
      'client_id':                      process.env.CLIENTID,
      'client_secret':                  process.env.CLIENT_SECRET,
        'isJourney':       'true',
        'taxBreakDown':    'true',
         'Host':            'api.pp.travelport.net',
        // 'Content-Length':  '970',
        'Connection':      'Keep-Alive',
         TraceId:           this.generateTraceId(),
      
      // travelportPlusSessionIdentifier: this.sessionId,
      // 'TVP-PCC-Core':                  this.pccCore,
      Authorization:                `Bearer ${bearerToken}`,
   
    };

    // ── Log headers to debug-xml/headers-<traceId>.json  updated ──────────────────────
    
    saveDebugLog(`headers-${headers.TraceId}.json`, headers);
    console.log('[Travelport] Headers logged →', `headers-${headers.TraceId}.json`);
    // ─────────────────────────────────────────────────────────────────────────

    return headers;
  },
};

module.exports = travelportConfig;