/**
 * Ersatz für das frühere `shopify.query(...)` der Sidekick-Erweiterung.
 * Läuft über Direct API Access (App Bridge hängt Token und Shop selbst an; kein Schlüssel im Frontend).
 * Rückgabeform wie bisher: { data, errors }.
 */
export interface GqlError {
  message: string;
  [key: string]: unknown;
}
export interface GqlResult {
  data?: any;
  errors?: any; // wie bisher lose typisiert (Aufrufer prüfen errors?.length)
  extensions?: any;
}

// Ohne Versionsangabe nimmt Direct API Access eine ältere Standardversion (dort fehlt @idempotent).
// Shopify dokumentiert die versionierte Form shopify:admin/api/<Version>/graphql.json.
export const API_VERSION = '2026-07';
export const GRAPHQL_URL = `shopify:admin/api/${API_VERSION}/graphql.json`;

const sleep = (ms: number): Promise<void> => new Promise((resolve) => setTimeout(resolve, ms));

function normalizeErrors(errors: unknown): GqlError[] | undefined {
  if (!errors) return undefined;
  if (typeof errors === 'string') return [{ message: errors }];
  if (Array.isArray(errors)) return errors as GqlError[];
  return [{ message: 'Unbekannter Shopify-Fehler' }];
}

const isThrottled = (errors?: GqlError[]): boolean =>
  !!errors?.some((e) => (e as any)?.extensions?.code === 'THROTTLED');

export async function shopifyQuery(
  query: string,
  options?: { variables?: Record<string, unknown> },
): Promise<GqlResult> {
  const maxAttempts = 4;
  for (let attempt = 1; ; attempt++) {
    const response = await fetch(GRAPHQL_URL, {
      method: 'POST',
      body: JSON.stringify({ query, variables: options?.variables }),
    });
    let payload: any = null;
    try {
      payload = await response.json();
    } catch {
      payload = null;
    }
    const errors = normalizeErrors(payload?.errors);
    // Nur bei Drosselung wiederholen: Die Anfrage wurde dann von Shopify nicht ausgeführt.
    if (isThrottled(errors) && attempt < maxAttempts) {
      await sleep(1000 * attempt);
      continue;
    }
    if (!response.ok && !errors) {
      return { data: null, errors: [{ message: `Shopify-Fehler ${response.status}` }] };
    }
    return { data: payload?.data ?? null, errors, extensions: payload?.extensions };
  }
}
