import { __ } from '@wordpress/i18n';
/**
 * Acces a l'API Convrail depuis l'administration WordPress.
 *
 * Tout passe par la passerelle du plugin (`convrail/v1/api/...`), jamais par l'API directement:
 * le jeton de pont reste sur le serveur WordPress. `apiFetch` ajoute le nonce REST de l'utilisateur
 * connecte, et la passerelle exige la capacite `manage_woocommerce`.
 */

import type {
  Billing,
  DashboardResponse,
  AlertsResponse,
  StoreGroup,
  StoreGroupResult,
  EventsResponse,
  FeedConfig,
  FeedRun,
  NotificationSettings,
  OpenAiFeed,
  ProductPerformance,
  FeedPreview,
  ProductScores,
  Shop,
  ShopStatus,
  VisibilityPanel,
  AdsOverview,
  ProductSetSuggestion,
  CopilotRule,
  CopilotActionRow,
} from './types';

interface ApiFetchOptions {
  path: string;
  method?: string;
  data?: unknown;
}

interface WordPressGlobal {
  apiFetch: <T>(options: ApiFetchOptions) => Promise<T>;
}

declare global {
  interface Window {
    wp: WordPressGlobal;
    /** Injecte par le plugin au chargement de la page (voir class-convrail-admin.php). */
    convrailAdmin?: {
      domain: string;
      connected: boolean;
      apiUrl: string;
      settingsUrl: string;
      adsManagerUrl: string;
      /** Pays de WooCommerce, deja traduits: code ISO -> nom affiche. */
      countries: Record<string, string>;
      /** Pays de la boutique (reglages WooCommerce), vide s'il n'est pas renseigne. */
      baseCountry?: string;
      /** Adresse de l'administrateur WordPress, pour preremplir le champ d'alerte. */
      adminEmail?: string;
      /** Nom de la boutique (Reglages > General), prerempli dans le flux tant que rien n'est enregistre. */
      storeName?: string;
      currency: string;
      /** Envois definitivement echoues, pour que rien ne se perde en silence. */
      syncError?: { page: number; status: number; at: number } | null;
      orderError?: { order: number; status: number; at: number } | null;
      /**
       * Plateforme qui affiche l'écran : WooCommerce (le plugin, par défaut) ou BigCommerce (l'API
       * sert l'écran dans l'admin du marchand, voir `hosts/bigcommerce.tsx`).
       */
      platform?: 'woocommerce' | 'bigcommerce';
      /** Adresse de la vitrine, quand elle diffère du domaine technique (`bc-<hash>`). */
      storefrontUrl?: string;
      /** Édition d'un produit dans l'admin de la plateforme ; `{id}` est remplacé. */
      productEditUrl?: string;
      /** L'app dans l'admin de la plateforme : retour après un paiement. */
      appUrl?: string;
    };
  }
}

export interface ApiError {
  status: number;
  code: string;
  message: string;
}

/** Erreur normalisee: l'ecran n'a qu'une forme a traiter, quelle que soit la couche qui a echoue. */
export function toApiError(error: unknown): ApiError {
  const raw = error as { code?: string; message?: string; data?: { status?: number } };
  const code = raw?.code ?? 'unknown';
  /*
   * Seuls les messages ecrits pour le marchand passent a l'ecran : ceux du plugin (codes
   * `convrail_*`, voir `Convrail_Rest::api_error`) et ceux de WordPress (`rest_*`, traduits). Une
   * exception JavaScript, une reponse qui n'est pas du JSON ou une coupure reseau donneraient sinon
   * « TypeError… » ou « The response is not a valid JSON response. » (constate cote Shopify le
   * 2026-09-26 : un message technique brut affiche au marchand).
   */
  const readable = code.startsWith('convrail_') || code.startsWith('rest_');
  return {
    status: raw?.data?.status ?? 0,
    code,
    message:
      readable && raw?.message
        ? raw.message
        : __('Something went wrong. Try again in a moment.', 'convrail'),
  };
}

export function bootstrap() {
  return (
    window.convrailAdmin ?? {
      domain: '',
      connected: false,
      apiUrl: '',
      settingsUrl: '',
      adsManagerUrl: 'https://ads.openai.com/settings/conversions',
      countries: {},
      currency: 'EUR',
    }
  );
}

async function call<T>(path: string, method: string, data?: unknown): Promise<T> {
  return window.wp.apiFetch<T>({
    path: `convrail/v1/api/${path}`,
    method,
    ...(data === undefined ? {} : { data }),
  });
}

export const api = {
  shop: () => call<Shop>('', 'GET'),
  status: () => call<ShopStatus>('status', 'GET'),
  setOnboarding: (body: Record<string, unknown>) => call<unknown>('onboarding', 'PUT', body),
  setTestMode: (testMode: boolean) => call<unknown>('test-mode', 'PUT', { testMode }),
  setConsentPosture: (consentPosture: string) =>
    call<unknown>('consent-posture', 'PUT', { consentPosture }),
  events: (limit = 50) => call<EventsResponse>(`events?limit=${limit}`, 'GET'),
  putCredentials: (pixelId: string, capiToken: string) =>
    call<{ validationStatus: string }>('credentials', 'PUT', { pixelId, capiToken }),
  putAdsKey: (adsApiKey: string, autoConfigure: boolean) =>
    call<{ ok: boolean; reason?: string; detail?: string }>('ads-credentials', 'PUT', {
      adsApiKey,
      autoConfigure,
    }),
  configureConversions: () =>
    call<{ ok: boolean; reason?: string; pixelId?: string; step?: string }>(
      'ads/configure',
      'POST',
      {},
    ),
  feedConfig: () => call<FeedConfig>('feed-config', 'GET'),
  saveFeedConfig: (body: Record<string, unknown>) =>
    call<{ ok: boolean; feed?: { ok: boolean; reason?: string; detail?: string } }>(
      'feed-config',
      'PUT',
      body,
    ),
  provisionFeed: () =>
    call<{ ok: boolean; reason?: string; detail?: string }>('feed/provision', 'POST', {}),
  generateFeed: () => call<{ queued: boolean }>('feed/generate', 'POST', {}),
  feedRuns: () =>
    call<{
      runs: FeedRun[];
      itemNames?: Record<string, { title: string; productId: string }>;
    }>('feed/runs', 'GET'),
  openaiFeed: () => call<OpenAiFeed>('feed/openai?limit=10', 'GET'),
  /**
   * Resynchronisation LOCALE: c'est le plugin qui pousse le catalogue, la plateforme ne peut pas
   * aller le chercher. L'ancienne version appelait la route Shopify et echouait a tous les coups.
   */
  syncCatalog: () =>
    window.wp.apiFetch<{ scheduled: boolean }>({ path: 'convrail/v1/sync', method: 'POST' }),
  dashboard: () => call<DashboardResponse>('dashboard', 'GET'),
  alerts: () => call<AlertsResponse>('alerts', 'GET'),
  billing: () => call<Billing>('billing', 'GET'),
  billingCheckout: (body: Record<string, unknown>) =>
    call<{ ok: boolean; url?: string; changed?: boolean; reason?: string }>(
      'billing/checkout',
      'POST',
      body,
    ),
  billingCancel: () =>
    call<{ ok: boolean; reason?: string; current?: Billing['current'] }>('billing/cancel', 'POST'),
  storeGroup: () => call<StoreGroup>('store-group', 'GET'),
  storeGroupAction: (
    action: 'code' | 'join' | 'remove' | 'leave',
    body: Record<string, string> = {},
  ) => call<StoreGroupResult>(`store-group/${action}`, 'POST', body),
  notificationSettings: () => call<NotificationSettings>('notification-settings', 'GET'),
  saveNotificationSettings: (body: Record<string, unknown>) =>
    call<NotificationSettings>('notification-settings', 'PUT', body),
  optimizeScores: (offset = 0, limit = 50) =>
    call<ProductScores>(`optimize/scores?offset=${offset}&limit=${limit}`, 'GET'),
  visibility: () => call<VisibilityPanel>('visibility', 'GET'),
  copilotAds: () => call<AdsOverview>('copilot/ads', 'GET'),
  copilotProductSet: (days = 30) =>
    call<ProductSetSuggestion>(`copilot/ads/product-set?days=${days}`, 'GET'),
  copilotApply: (body: Record<string, unknown>) =>
    call<{ ok: boolean; reason?: string; detail?: string }>('copilot/ads/apply', 'POST', body),
  copilotHistory: () => call<{ actions: CopilotActionRow[] }>('copilot/ads/history', 'GET'),
  copilotRules: () => call<{ rules: CopilotRule[] }>('copilot/rules', 'GET'),
  saveCopilotRule: (body: Record<string, unknown>) =>
    call<{ kind: string; enabled: boolean }>('copilot/rules', 'PUT', body),
  visibilitySuggestions: () => call<{ suggestions: string[] }>('visibility/suggestions', 'GET'),
  // Pays vide: l'API retient celui de la boutique.
  addVisibilityPrompt: (text: string, country: string) =>
    call<{ ok: boolean; reason?: string; limit?: number; upgradeTo?: string }>(
      'visibility/prompts',
      'POST',
      country ? { text, country } : { text },
    ),
  removeVisibilityPrompt: (id: string) =>
    call<{ ok: boolean }>('visibility/prompts/stop', 'POST', { id }),
  feedPreview: (productId?: string) =>
    call<FeedPreview>(
      productId
        ? `optimize/preview?productId=${encodeURIComponent(productId)}`
        : 'optimize/preview',
      'GET',
    ),
  rewrite: (
    productExternalId: string,
    apply: boolean,
    reviewed?: { title?: string | undefined; description?: string | undefined },
  ) =>
    call<{ suggestion: { title?: string; description?: string }; applied: boolean }>(
      'optimize/rewrite',
      'POST',
      { productExternalId, apply, ...(reviewed ?? {}) },
    ),
  copilot: (days = 30) =>
    call<{ products: ProductPerformance[]; costsKnown?: boolean; spendKnown?: boolean }>(
      `copilot/products?days=${days}`,
      'GET',
    ),
};
