import { GATEWAY_URL } from '../auth/authConfig';

// ── Helpers (same pattern as wizardApi.js) ──

function authHeaders(sessionToken) {
  const h = { 'Content-Type': 'application/json' };
  if (sessionToken) h['Authorization'] = `Bearer ${sessionToken}`;
  const tid = localStorage.getItem('adplatform_tenantId');
  if (tid) h['X-Tenant-Id'] = tid;
  return h;
}

async function gw(method, path, body, sessionToken) {
  try {
    const opts = { method, headers: authHeaders(sessionToken) };
    if (body && method !== 'GET') opts.body = JSON.stringify(body);
    const res = await fetch(`${GATEWAY_URL}${path}`, opts);
    const data = await res.json().catch(() => null);
    return {
      ok: res.ok && data?.ok !== false,
      status: res.status,
      data,
      error: res.ok ? null : (data?.error || data?.message || `HTTP ${res.status}`)
    };
  } catch (e) {
    return { ok: false, status: 0, data: null, error: e.message };
  }
}

// ── Channel Forecast ──

/**
 * Get channel performance estimates for the wizard budget step.
 * Calls Gateway POST /api/forecast/channel-estimate.
 *
 * @param {object} params
 * @param {string} params.objective       - awareness, traffic, leads, sales
 * @param {string} params.businessCategory
 * @param {string[]} params.keywords      - from URL analysis (Step 1)
 * @param {object} params.geoTargeting    - { zipCodes, radiusMiles, geoTargetIds }
 * @param {object} params.audience        - { ageMin, ageMax, genders, interests }
 * @param {number} params.monthlyBudget
 * @param {string[]} params.channels      - selected channels from Step 3
 * @param {string} sessionToken
 */
export function getChannelForecast(params, sessionToken) {
  return gw('POST', '/api/forecast/channel-estimate', params, sessionToken);
}
