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

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

// ── Wizard Config (DB-driven categories + objectives) ──

export function getWizardConfig(sessionToken) {
  return gw('GET', '/api/wizard/config', null, sessionToken);
}

// ── Wizard CRUD ──

export function createWizard(name, url, sessionToken) {
  return gw('POST', '/api/wizard', { name, url }, sessionToken);
}

export function getWizard(wizardId, sessionToken) {
  return gw('GET', `/api/wizard/${wizardId}`, null, sessionToken);
}

export function listWizards(sessionToken, status, limit) {
  const qs = new URLSearchParams();
  if (status) qs.set('status', status);
  if (limit) qs.set('limit', String(limit));
  const q = qs.toString();
  return gw('GET', `/api/wizard${q ? '?' + q : ''}`, null, sessionToken);
}

export function deleteWizard(wizardId, sessionToken, force = false) {
  return gw('DELETE', `/api/wizard/${wizardId}${force ? '?force=true' : ''}`, null, sessionToken);
}

// ── Step Operations ──

export function updateStep(wizardId, step, data, sessionToken, name) {
  return gw('PUT', `/api/wizard/${wizardId}/step/${step}`, { data, name }, sessionToken);
}

export function setStep(wizardId, step, sessionToken) {
  return gw('PATCH', `/api/wizard/${wizardId}/step/${step}`, null, sessionToken);
}

// ── Review & Submit ──

export function getSummary(wizardId, sessionToken) {
  return gw('GET', `/api/wizard/${wizardId}/summary`, null, sessionToken);
}

export function submitWizard(wizardId, sessionToken, network = 'google') {
  return gw('POST', `/api/wizard/${wizardId}/submit`, { network }, sessionToken);
}

export function updateStatus(wizardId, status, sessionToken) {
  return gw('PATCH', `/api/wizard/${wizardId}/status`, { status }, sessionToken);
}

// ── Creative Service Calls (via execution gateway) ──

export function analyzeUrl(url, sessionToken) {
  return callService('creative', 'AnalyzeUrl', { url }, { sessionToken });
}

export function generateAssets(analysis, sessionToken) {
  return callService('creative', 'GenerateAssets', { analysis }, { sessionToken });
}

export function getImages(analysis, sessionToken) {
  return callService('creative', 'GetImages', { analysis }, { sessionToken });
}

export function createDraft(url, sessionToken) {
  return callService('creative', 'CreateDraft', { url }, { sessionToken });
}

// ── Allocation Recommendation (audience-adjusted) ──

export function getAudienceRecommendation(businessCategory, objective, ageSkew, marketScope, sessionToken) {
  const body = { businessCategory, objective };
  if (ageSkew) body.ageSkew = ageSkew;
  if (marketScope) body.marketScope = marketScope;
  return gw('POST', '/api/wizard/recommend', body, sessionToken);
}

// ── Audience Service Calls ──

export function getAudienceSegments(sessionToken) {
  return callService('google', 'GetAudienceSegments', {}, { sessionToken });
}

export function searchGeoTargets(query, sessionToken, countryCode = 'US', maxResults = 10) {
  return callService('google', 'SearchGeoTargets', { query, countryCode, maxResults }, { sessionToken });
}

// ── Census Demographics ──

export function getDemographics(zcta, sessionToken) {
  return gw('GET', `/api/demographics/${zcta}`, null, sessionToken);
}

export function searchDemographics(criteria, sessionToken) {
  return gw('POST', '/api/demographics/search', criteria, sessionToken);
}
