/**
 * Utility to parse raw Meta / Facebook Graph API error messages into
 * user-friendly, actionable explanations with step-by-step resolution guidance.
 */

export interface ParsedMetaError {
  title: string;
  message: string;
  actionableStep?: string;
  rawError?: string;
  actionUrl?: string;
  actionLabel?: string;
}

export function parseMetaErrorMessage(rawError?: string | null): ParsedMetaError {
  if (!rawError || !rawError.trim()) {
    return {
      title: 'Sync Error',
      message: 'An unexpected error occurred while communicating with Facebook Commerce.',
      rawError: rawError || undefined,
    };
  }

  const errStr = rawError.trim();

  // 0. Shopify Store Permission / 403 Forbidden / Scope Error
  if (
    errStr.includes('403') ||
    errStr.toLowerCase().includes('forbidden') ||
    errStr.toLowerCase().includes('read_products') ||
    errStr.toLowerCase().includes('re-authorization required') ||
    errStr.toLowerCase().includes('shopify product sync error') ||
    errStr.toLowerCase().includes('shopify rest api responded with http 403') ||
    errStr.toLowerCase().includes('requires merchant approval')
  ) {
    const domainMatch = errStr.match(/([a-zA-Z0-9-]+\.myshopify\.com)/i);
    const shop = domainMatch ? domainMatch[1] : undefined;
    const reauthUrl = shop ? `/api/auth/shopify?shop=${shop}` : '/api/auth/shopify';

    return {
      title: 'Shopify Store Permission Required (HTTP 403 Forbidden)',
      message:
        'Your Shopify store has not granted the required permission ("read_products") to access store products.',
      actionableStep:
        'Click the button below to re-authorize the app on your Shopify store and approve product access in 1 click.',
      actionUrl: reauthUrl,
      actionLabel: 'Re-authorize Shopify Store Now',
      rawError: errStr,
    };
  }

  // 1. Permission Error (#200) or missing permissions
  if (
    errStr.includes('#200') ||
    errStr.toLowerCase().includes('permissions error') ||
    errStr.toLowerCase().includes('missing permissions') ||
    errStr.toLowerCase().includes('permission')
  ) {
    return {
      title: 'Facebook Catalog Permission Required',
      message:
        'Your connected Facebook account does not have "Manage Catalog" (Full Control) permission for this catalog in Meta Business Suite.',
      actionableStep:
        'How to fix: Go to Meta Business Suite (business.facebook.com) > Settings > Data Sources > Catalogs > Click on this Catalog > Click "Assign people" > Select your account and enable "Full Control (Manage Catalog)".',
      rawError: errStr,
    };
  }

  // 2. Unsupported post request / Object does not exist / Not found
  if (
    errStr.toLowerCase().includes('unsupported post request') ||
    errStr.toLowerCase().includes('does not exist') ||
    errStr.toLowerCase().includes('object with id')
  ) {
    return {
      title: 'Catalog Not Found in Facebook',
      message:
        'This Facebook Catalog ID does not exist under your connected Business Portfolio or was created by a different unlinked account.',
      actionableStep:
        'How to fix: In your app Catalog Settings, select an existing catalog from your Business Portfolio dropdown or choose "Create new Facebook Catalog".',
      rawError: errStr,
    };
  }

  // 3. OAuth / Token Expiration
  if (
    errStr.toLowerCase().includes('oauthexception') ||
    errStr.toLowerCase().includes('session has expired') ||
    errStr.toLowerCase().includes('access token') ||
    errStr.toLowerCase().includes('invalid token')
  ) {
    return {
      title: 'Facebook Authentication Expired',
      message: 'Your Facebook connection token has expired or has been invalidated by Meta.',
      actionableStep: 'How to fix: Go to the Onboarding / Settings tab and click "Reconnect Facebook Account".',
      rawError: errStr,
    };
  }

  // 4. Rate Limit (#32 or #17 or #613)
  if (
    errStr.includes('#32') ||
    errStr.includes('#17') ||
    errStr.includes('#613') ||
    errStr.toLowerCase().includes('rate limit')
  ) {
    return {
      title: 'Meta API Rate Limit Reached',
      message: 'Too many requests were sent to Facebook within a short window.',
      actionableStep: 'Please wait a few minutes and try syncing again.',
      rawError: errStr,
    };
  }

  // 5. Item Type / Missing Parameter (#100)
  if (errStr.includes('#100') || errStr.toLowerCase().includes('parameter')) {
    return {
      title: 'Catalog Data Format Error',
      message: `Facebook reported a parameter validation error: ${errStr.replace(/\(#\d+\)\s*/g, '')}`,
      actionableStep: 'Please verify your catalog settings and variant options.',
      rawError: errStr,
    };
  }

  return {
    title: 'Facebook Sync Error',
    message: errStr,
    rawError: errStr,
  };
}
