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

// ── Helpers ──

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 };
  }
}

function qs(params) {
  const sp = new URLSearchParams();
  Object.entries(params).forEach(([k, v]) => {
    if (v != null) sp.set(k, String(v));
  });
  const s = sp.toString();
  return s ? '?' + s : '';
}

// ── Campaign Intelligence ──

export function getCampaignHealth(sessionToken) {
  return gw('GET', '/api/intelligence/health', null, sessionToken);
}

export function getBudgetPacing(initiativeId, sessionToken) {
  return gw('GET', `/api/intelligence/${initiativeId}/pacing`, null, sessionToken);
}

export function getPostCampaignReport(initiativeId, sessionToken) {
  return gw('GET', `/api/intelligence/${initiativeId}/report`, null, sessionToken);
}

// ── Recommendations ──

export function getRecommendations(sessionToken, status, limit) {
  return gw('GET', `/api/recommendations${qs({ status, limit })}`, null, sessionToken);
}

export function getInitiativeRecommendations(initiativeId, sessionToken, status) {
  return gw('GET', `/api/recommendations/initiative/${initiativeId}${qs({ status })}`, null, sessionToken);
}

export function dismissRecommendation(recommendationId, sessionToken) {
  return gw('POST', `/api/recommendations/${recommendationId}/dismiss`, {}, sessionToken);
}

export function resolveRecommendation(recommendationId, sessionToken) {
  return gw('POST', `/api/recommendations/${recommendationId}/resolve`, {}, sessionToken);
}
