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

/**
 * Generic API fetch helper.
 */
export async function callApi(url, options = {}) {
  const fullUrl = url.startsWith('http') ? url : `${GATEWAY_URL}${url}`;

  try {
    const response = await fetch(fullUrl, {
      method: options.method || 'GET',
      headers: {
        'Content-Type': 'application/json',
        ...options.headers
      },
      body: options.body ? JSON.stringify(options.body) : undefined
    });

    const data = await response.json().catch(() => null);

    return {
      ok: response.ok,
      status: response.status,
      data,
      error: response.ok ? null : (data?.message || data?.error || `HTTP ${response.status}`)
    };
  } catch (error) {
    return {
      ok: false,
      status: 0,
      data: null,
      error: error.message || 'Network error'
    };
  }
}

/**
 * Execute a provider operation through the Gateway.
 *
 * @param {string} provider  - Ad platform provider: google, meta, msads
 * @param {string} operation - Operation name: list, get, ping, getStats, etc.
 * @param {object} params    - Additional params spread into body (tenantId, payload, etc.)
 * @param {object} options   - { sessionToken, tenantId }
 */
export async function callService(provider, operation, params = {}, options = {}) {
  const { sessionToken, tenantId } = options;

  console.log('[API] callService:', provider, operation);

  const headers = {
    'Content-Type': 'application/json'
  };

  if (sessionToken) {
    headers['Authorization'] = `Bearer ${sessionToken}`;
  }

  const effectiveTenantId = tenantId || localStorage.getItem('adplatform_tenantId');
  if (effectiveTenantId) {
    headers['X-Tenant-Id'] = effectiveTenantId;
  }

  const url = `${GATEWAY_URL}/api/execution/request`;
  const body = {
    provider,
    operation,
    payload: params
  };

  console.log('[API] Request URL:', url);
  console.log('[API] Request body:', body);

  try {
    const response = await fetch(url, {
      method: 'POST',
      headers,
      body: JSON.stringify(body)
    });

    console.log('[API] Response status:', response.status);

    const data = await response.json().catch(() => null);

    return {
      ok: response.ok && data?.ok !== false,
      status: response.status,
      data,
      error: response.ok ? null : (data?.message || data?.error || `HTTP ${response.status}`)
    };
  } catch (error) {
    console.error('[API] Request error:', error);
    return {
      ok: false,
      status: 0,
      data: null,
      error: error.message || 'Network error'
    };
  }
}

/**
 * Gateway health check (no auth required).
 */
export async function gatewayHealth() {
  return callApi('/health');
}

export default { callApi, callService, gatewayHealth };
