import { CommerceConnector } from '../interfaces/connector.interface';
import { UniversalProduct, UniversalCategory, UniversalOrder } from '../interfaces/universal-models.interface';
import axios, { AxiosInstance } from 'axios';
import * as crypto from 'crypto';

export class WooCommerceConnector implements CommerceConnector {
  private axiosClient: AxiosInstance | null = null;
  private readonly isSandbox: boolean = false;
  private readonly storeUrl: string;
  private readonly consumerKey: string;
  private readonly consumerSecret: string;
  private readonly isHttps: boolean = false;
  // WordPress home URL without trailing slash — used as OAuth base URL
  private readonly oauthBaseUrl: string = '';

  constructor(credentials: Record<string, any>) {
    this.storeUrl = credentials.storeUrl || '';
    this.consumerKey = (credentials.consumerKey || '').trim();
    this.consumerSecret = (credentials.consumerSecret || '').trim();
    this.isSandbox =
      credentials.isSandbox ||
      this.storeUrl.includes('sandbox.local') ||
      this.consumerKey === 'ck_sandbox';

    if (!this.isSandbox && this.storeUrl) {
      const cleanUrl = this.storeUrl.endsWith('/') ? this.storeUrl : `${this.storeUrl}/`;
      this.isHttps = cleanUrl.startsWith('https://');
      // OAuth base URL = WordPress home URL without trailing slash
      this.oauthBaseUrl = cleanUrl.replace(/\/$/, '');

      if (this.isHttps) {
        // HTTPS → Basic Auth header (most reliable, WooCommerce calls perform_basic_auth)
        const authHeader = Buffer.from(`${this.consumerKey}:${this.consumerSecret}`).toString('base64');
        this.axiosClient = axios.create({
          baseURL: cleanUrl,
          headers: {
            Authorization: `Basic ${authHeader}`,
            'Content-Type': 'application/json',
          },
          timeout: 15000,
        });
      } else {
        // HTTP → OAuth 1.0a HMAC-SHA256 signing.
        //
        // WHY: WooCommerce source (class-wc-rest-authentication.php) only calls
        // perform_basic_auth() when is_ssl() is true. Over plain HTTP it calls
        // perform_oauth_authentication() exclusively, which requires oauth_consumer_key
        // + oauth_signature in the request.
        //
        // WHY NOT consumer_key/consumer_secret params: WooCommerce's get_oauth_parameters()
        // filters to only params starting with "oauth_", so raw consumer_key params are ignored.
        //
        // WooCommerce-specific base string format (non-standard vs RFC 5849):
        // It encodes each param key/value individually with rawurlencode, then joins
        // them as "key%3Dvalue" separated by "%26" WITHOUT double-encoding the result.
        // Standard OAuth would double-encode the entire param string.
        this.axiosClient = axios.create({
          baseURL: cleanUrl,
          headers: { 'Content-Type': 'application/json' },
          timeout: 15000,
        });

        this.axiosClient.interceptors.request.use((config) => {
          const method = (config.method || 'GET').toUpperCase();
          const urlPath = config.url || '';
          const isRestRoute = urlPath.startsWith('?rest_route=');

          // Determine the canonical base URL used for OAuth signing
          // For ?rest_route= style: base URL is the root URL with a trailing slash (e.g., http://host/kioskoshop/)
          // For pretty style: base URL is the full path without query parameters
          const oauthBaseUrl = isRestRoute
            ? `${cleanUrl}`
            : `${cleanUrl}${urlPath.replace(/^\//, '')}`;

          // Collect all query params
          const reqParams: Record<string, string> = {};
          if (config.params) {
            Object.entries(config.params).forEach(([k, v]) => { reqParams[k] = String(v); });
          }

          // For ?rest_route= style: extract rest_route from URL string into params for signing
          if (urlPath.startsWith('?')) {
            new URLSearchParams(urlPath.substring(1)).forEach((v, k) => { reqParams[k] = v; });
          }

          // Build OAuth params (omit version as per standard practices)
          const oauthParams: Record<string, string> = {
            oauth_consumer_key: this.consumerKey,
            oauth_nonce: crypto.randomBytes(16).toString('hex'),
            oauth_signature_method: 'HMAC-SHA256',
            oauth_timestamp: Math.floor(Date.now() / 1000).toString(),
          };

          // Merge all params for signature
          const allParams = { ...reqParams, ...oauthParams };

          // Build OAuth 1.0a standard parameter string (keys and values sorted and encoded)
          const sortedPairs = Object.entries(allParams)
            .sort(([a], [b]) => a < b ? -1 : a > b ? 1 : 0)
            .map(([k, v]) => `${encodeURIComponent(k)}=${encodeURIComponent(v)}`);
          const paramString = sortedPairs.join('&');

          // Standard double-encoding for the parameters string
          const normalizedParams = encodeURIComponent(paramString);

          // Signing key = encodeURIComponent(consumerSecret) + '&'
          const signingKey = `${encodeURIComponent(this.consumerSecret)}&`;
          // Base string: METHOD & encoded(base_url) & encoded(param_string)
          const baseString = `${method}&${encodeURIComponent(oauthBaseUrl)}&${normalizedParams}`;
          const signature = crypto.createHmac('sha256', signingKey).update(baseString).digest('base64');

          const allSigned = { ...oauthParams, oauth_signature: signature };

          if (urlPath.startsWith('?')) {
            // Write rest_route with literal slashes directly in URL to prevent Axios encoding
            const restRouteValue = reqParams['rest_route'] || '';
            const extraParams = Object.entries(reqParams)
              .filter(([k]) => k !== 'rest_route')
              .map(([k, v]) => `${encodeURIComponent(k)}=${encodeURIComponent(v)}`)
              .join('&');
            const oauthQuery = Object.entries(allSigned)
              .map(([k, v]) => `${encodeURIComponent(k)}=${encodeURIComponent(v)}`)
              .join('&');
            const parts = [`rest_route=${restRouteValue}`, extraParams, oauthQuery].filter(Boolean);
            config.url = `?${parts.join('&')}`;
            config.params = undefined;
          } else {
            config.params = { ...reqParams, ...allSigned };
          }

          const base = (config.baseURL || '').replace(/\/$/, '');
          console.log('[WooCommerce] Request URL:', `${base}${config.url || ''}`.substring(0, 220));
          return config;
        });
      }
    }
  }


  private useRestRoute = false;

  private getRequestUrl(endpoint: string): string {
    if (this.useRestRoute) {
      return `?rest_route=/wc/v3/${endpoint}`;
    } else {
      return `wp-json/wc/v3/${endpoint}`;
    }
  }

  async testConnection(): Promise<boolean> {
    if (this.isSandbox) {
      return true;
    }
    if (!this.axiosClient) return false;

    // Test 1: Try default custom permalinks path (wp-json/wc/v3)
    try {
      this.useRestRoute = false;
      const url = this.getRequestUrl('products');
      const response = await this.axiosClient.get(url, { params: { per_page: 1 } });
      if (response.status === 200) {
        return true;
      }
    } catch (err: any) {
      console.warn('WooCommerce testConnection custom permalinks failed, trying fallback:', err.message);
    }

    // Test 2: Try plain permalinks path (?rest_route=/wc/v3)
    try {
      this.useRestRoute = true;
      const url = this.getRequestUrl('products');
      const response = await this.axiosClient.get(url, { params: { per_page: 1 } });
      if (response.status === 200) {
        console.log('WooCommerce connection successful using Plain Permalinks (?rest_route=/wc/v3) fallback!');
        return true;
      }
    } catch (err: any) {
      console.error('WooCommerce testConnection plain permalinks failed:', {
        message: err.message,
        code: err.code,
        response: err.response?.data,
        status: err.response?.status,
      });
      // Revert to default
      this.useRestRoute = false;
    }

    return false;
  }

  async fetchProducts(): Promise<UniversalProduct[]> {
    if (this.isSandbox) {
      return this.getMockProducts();
    }

    if (!this.axiosClient) {
      throw new Error('WooCommerce API client is not configured');
    }

    try {
      const response = await this.axiosClient.get(this.getRequestUrl('products'), {
        params: { per_page: 50, status: 'publish' },
      });

      return response.data.map((p: any) => {
        const catNames = p.categories?.map((cat: any) => cat.name).join(', ') || '';
        let description = p.description?.replace(/<[^>]*>/g, '') || '';
        if (catNames) {
          description = `${description}\n\nCategories: ${catNames}`;
        }

        return {
          externalId: String(p.id),
          name: p.name,
          description: description || undefined,
          sku: p.sku || undefined,
          price: parseFloat(p.price || p.regular_price || '0'),
          currency: 'USD', // WooCommerce default currency is checked on WooCommerce side, we can normalize
          stockQuantity: p.stock_quantity ?? undefined,
          stockStatus: p.stock_status === 'instock' ? 'instock' : 'outofstock',
          imageUrl: p.images?.[0]?.src || undefined,
          variants: p.variations?.map((varId: number) => ({
            externalId: String(varId),
            name: `${p.name} - Option ${varId}`,
            price: parseFloat(p.price || '0'),
            stockStatus: 'instock',
          })) || [],
        };
      });
    } catch (err: any) {
      throw new Error(`Failed to fetch products from WooCommerce: ${err.message}`);
    }
  }

  async fetchCategories(): Promise<UniversalCategory[]> {
    if (this.isSandbox) {
      return [
        { externalId: 'cat_electronics', name: 'Electronics' },
        { externalId: 'cat_audio', name: 'Audio Devices', parentId: 'cat_electronics' },
        { externalId: 'cat_wearables', name: 'Wearables', parentId: 'cat_electronics' },
        { externalId: 'cat_accessories', name: 'Accessories' },
      ];
    }

    if (!this.axiosClient) {
      throw new Error('WooCommerce API client is not configured');
    }

    try {
      const response = await this.axiosClient.get(this.getRequestUrl('products/categories'), {
        params: { per_page: 50 },
      });

      return response.data.map((c: any) => ({
        externalId: String(c.id),
        name: c.name,
        parentId: c.parent ? String(c.parent) : undefined,
      }));
    } catch (err: any) {
      throw new Error(`Failed to fetch categories from WooCommerce: ${err.message}`);
    }
  }

  private normalizePublicImageUrl(url?: string): string | undefined {
    if (!url || typeof url !== 'string' || !url.trim().startsWith('http')) {
      return undefined;
    }
    let cleanUrl = url.trim();
    const publicBase = process.env.PUBLIC_URL || process.env.FRONTEND_URL || '';
    if ((cleanUrl.includes('://localhost') || cleanUrl.includes('://127.0.0.1')) && publicBase && publicBase.startsWith('http')) {
      const match = cleanUrl.match(/\/(uploads\/.*)$/);
      if (match) {
        cleanUrl = `${publicBase.replace(/\/$/, '')}/${match[1]}`;
      }
    }
    if (cleanUrl.includes('://localhost') || cleanUrl.includes('://127.0.0.1')) {
      return undefined; // Do not send unreachable localhost URLs to remote external servers
    }
    return cleanUrl;
  }

  async createProduct(product: UniversalProduct): Promise<{ externalId: string }> {
    if (this.isSandbox) {
      return { externalId: `mock_wc_${Math.floor(10000 + Math.random() * 90000)}` };
    }

    if (!this.axiosClient) {
      throw new Error('WooCommerce API client is not configured');
    }

    try {
      const payload: any = {
        name: product.name,
        type: 'simple',
        regular_price: String(product.price || '0'),
        description: product.description || '',
        status: 'publish',
      };

      if (product.sku && product.sku.trim() !== '') {
        payload.sku = product.sku.trim();
      }

      if (product.stockQuantity !== null && product.stockQuantity !== undefined && !isNaN(product.stockQuantity)) {
        payload.manage_stock = true;
        payload.stock_quantity = Number(product.stockQuantity);
        payload.stock_status = Number(product.stockQuantity) > 0 ? 'instock' : 'outofstock';
      } else {
        payload.manage_stock = false;
        payload.stock_status = product.stockStatus === 'instock' ? 'instock' : 'outofstock';
      }

      const cleanImage = this.normalizePublicImageUrl(product.imageUrl);
      if (cleanImage) {
        payload.images = [{ src: cleanImage }];
      }

      try {
        const response = await this.axiosClient.post(this.getRequestUrl('products'), payload);
        return { externalId: String(response.data.id) };
      } catch (postErr: any) {
        let currentErr = postErr;
        const detailStr = String(currentErr.response?.data?.message || currentErr.message || '').toLowerCase();
        if (payload.images && (detailStr.includes('remote image') || detailStr.includes('valid url') || detailStr.includes('not found') || detailStr.includes('image') || currentErr.response?.status === 400)) {
          delete payload.images;
          try {
            const retryResponse = await this.axiosClient.post(this.getRequestUrl('products'), payload);
            return { externalId: String(retryResponse.data.id) };
          } catch (retryErr: any) {
            currentErr = retryErr;
          }
        }
        const errDetailStr = String(currentErr.response?.data?.message || currentErr.response?.data?.code || currentErr.message || '').toLowerCase();
        if (product.sku && (errDetailStr.includes('already present') || errDetailStr.includes('sku') || errDetailStr.includes('exists') || currentErr.response?.data?.code === 'product_invalid_sku')) {
          try {
            const searchRes = await this.axiosClient.get(this.getRequestUrl('products'), { params: { sku: product.sku.trim() } });
            if (Array.isArray(searchRes.data) && searchRes.data.length > 0 && searchRes.data[0].id) {
              const existingId = String(searchRes.data[0].id);
              await this.updateProduct(existingId, product);
              return { externalId: existingId };
            }
          } catch (searchErr) {
            // ignore lookup failure and throw original
          }
        }
        throw currentErr;
      }
    } catch (err: any) {
      const detail = err.response?.data?.message || err.response?.data?.code || (typeof err.response?.data === 'object' ? JSON.stringify(err.response.data) : null) || err.message;
      throw new Error(`Failed to create product in WooCommerce: ${detail}`);
    }
  }

  async updateProduct(externalProductId: string, product: UniversalProduct): Promise<boolean> {
    if (this.isSandbox) {
      return true;
    }

    if (!this.axiosClient) {
      throw new Error('WooCommerce API client is not configured');
    }

    try {
      const payload: any = {
        name: product.name,
        regular_price: String(product.price || '0'),
        description: product.description || '',
      };

      if (product.sku && product.sku.trim() !== '') {
        payload.sku = product.sku.trim();
      }

      if (product.stockQuantity !== null && product.stockQuantity !== undefined && !isNaN(product.stockQuantity)) {
        payload.manage_stock = true;
        payload.stock_quantity = Number(product.stockQuantity);
        payload.stock_status = Number(product.stockQuantity) > 0 ? 'instock' : 'outofstock';
      } else {
        payload.manage_stock = false;
        payload.stock_status = product.stockStatus === 'instock' ? 'instock' : 'outofstock';
      }

      const cleanImage = this.normalizePublicImageUrl(product.imageUrl);
      if (cleanImage) {
        payload.images = [{ src: cleanImage }];
      }

      try {
        await this.axiosClient.put(this.getRequestUrl(`products/${externalProductId}`), payload);
      } catch (putErr: any) {
        if (putErr.response?.status === 404) {
          await this.createProduct(product);
          return true;
        }
        let currentErr = putErr;
        const detailStr = String(currentErr.response?.data?.message || currentErr.message || '').toLowerCase();
        if (payload.images && (detailStr.includes('remote image') || detailStr.includes('valid url') || detailStr.includes('not found') || detailStr.includes('image') || currentErr.response?.status === 400)) {
          delete payload.images;
          try {
            await this.axiosClient.put(this.getRequestUrl(`products/${externalProductId}`), payload);
            return true;
          } catch (retryErr: any) {
            currentErr = retryErr;
          }
        }
        const errDetailStr = String(currentErr.response?.data?.message || currentErr.response?.data?.code || currentErr.message || '').toLowerCase();
        if (payload.sku && (errDetailStr.includes('already present') || errDetailStr.includes('sku') || errDetailStr.includes('exists') || currentErr.response?.data?.code === 'product_invalid_sku')) {
          try {
            const searchRes = await this.axiosClient.get(this.getRequestUrl('products'), { params: { sku: payload.sku } });
            if (Array.isArray(searchRes.data) && searchRes.data.length > 0 && searchRes.data[0].id) {
              const targetId = String(searchRes.data[0].id);
              delete payload.sku;
              await this.axiosClient.put(this.getRequestUrl(`products/${targetId}`), payload);
              return true;
            }
          } catch (e) {
            delete payload.sku;
            await this.axiosClient.put(this.getRequestUrl(`products/${externalProductId}`), payload);
            return true;
          }
        }
        throw currentErr;
      }
      return true;
    } catch (err: any) {
      if (err.response?.status === 404) {
        await this.createProduct(product);
        return true;
      }
      const detail = err.response?.data?.message || err.response?.data?.code || (typeof err.response?.data === 'object' ? JSON.stringify(err.response.data) : null) || err.message;
      throw new Error(`Failed to update product in WooCommerce (${externalProductId}): ${detail}`);
    }
  }

  async deleteProduct(externalProductId: string, product?: any): Promise<boolean> {
    if (this.isSandbox) {
      return true;
    }

    if (!this.axiosClient) {
      throw new Error('WooCommerce API client is not configured');
    }

    let deletedOrFound = false;

    // 1. If externalProductId looks like a WooCommerce numeric ID, try direct deletion
    if (/^\d+$/.test(externalProductId)) {
      try {
        await this.axiosClient.delete(this.getRequestUrl(`products/${externalProductId}`), {
          params: { force: true },
        });
        deletedOrFound = true;
      } catch (err: any) {
        if (err.response?.status === 404) {
          deletedOrFound = true;
        } else {
          const detailStr = String(err.response?.data?.message || err.response?.data?.code || err.message || '').toLowerCase();
          if (!detailStr.includes('invalid') && !detailStr.includes('not found')) {
            throw err;
          }
        }
      }
    }

    // 2. Also search by SKU to delete any matching product inside WooCommerce (essential when externalProductId is a Meta ID or local UUID)
    const skuToSearch = product?.sku || (!/^\d+$/.test(externalProductId) ? externalProductId : null);
    if (skuToSearch && typeof skuToSearch === 'string' && skuToSearch.trim()) {
      try {
        const searchRes = await this.axiosClient.get(this.getRequestUrl('products'), {
          params: { sku: skuToSearch.trim() },
        });
        if (Array.isArray(searchRes.data) && searchRes.data.length > 0) {
          for (const wcProd of searchRes.data) {
            try {
              await this.axiosClient.delete(this.getRequestUrl(`products/${wcProd.id}`), {
                params: { force: true },
              });
              deletedOrFound = true;
            } catch {
              // Ignore if already deleted
            }
          }
        }
      } catch {
        // Ignore search errors
      }
    }

    return true;
  }

  async checkStock(externalProductId: string, externalVariantId?: string): Promise<number> {
    if (this.isSandbox) {
      return 15; // Mock stock quantity
    }

    if (!this.axiosClient) return 0;

    try {
      if (externalVariantId) {
        const response = await this.axiosClient.get(
          this.getRequestUrl(`products/${externalProductId}/variations/${externalVariantId}`)
        );
        return response.data.stock_quantity ?? 10;
      }
      const response = await this.axiosClient.get(this.getRequestUrl(`products/${externalProductId}`));
      return response.data.stock_quantity ?? 10;
    } catch {
      return 0;
    }
  }

  async createOrder(order: UniversalOrder): Promise<{ externalOrderId: string; orderNumber: string }> {
    if (this.isSandbox) {
      const randId = Math.floor(1000 + Math.random() * 9000);
      return {
        externalOrderId: `wc_mock_${randId}`,
        orderNumber: String(randId),
      };
    }

    if (!this.axiosClient) {
      throw new Error('WooCommerce API client is not configured');
    }

    try {
      const lineItems = order.items.map((item) => ({
        product_id: parseInt(item.externalProductId),
        variation_id: item.externalVariantId ? parseInt(item.externalVariantId) : undefined,
        quantity: item.quantity,
      }));

      const orderPayload = {
        payment_method: 'whatsapp_hub',
        payment_method_title: 'WhatsApp Commerce Hub (Paynow/PesePay)',
        set_paid: false,
        billing: {
          first_name: order.customerName,
          phone: order.customerPhone,
          address_1: order.deliveryAddress || 'WhatsApp Checkout',
        },
        shipping: {
          first_name: order.customerName,
          address_1: order.deliveryAddress || 'WhatsApp Checkout',
        },
        line_items: lineItems,
      };

      const response = await this.axiosClient.post(this.getRequestUrl('orders'), orderPayload);
      return {
        externalOrderId: String(response.data.id),
        orderNumber: String(response.data.number),
      };
    } catch (err: any) {
      throw new Error(`Failed to create WooCommerce order: ${err.response?.data?.message || err.message}`);
    }
  }

  async updateOrderStatus(externalOrderId: string, status: string): Promise<boolean> {
    if (this.isSandbox) {
      return true;
    }

    if (!this.axiosClient) return false;

    try {
      let wcStatus = 'pending';
      if (status === 'PAID') wcStatus = 'processing';
      if (status === 'COMPLETED') wcStatus = 'completed';
      if (status === 'CANCELLED') wcStatus = 'cancelled';
      if (status === 'FAILED') wcStatus = 'failed';

      await this.axiosClient.put(this.getRequestUrl(`orders/${externalOrderId}`), { status: wcStatus });
      return true;
    } catch {
      return false;
    }
  }

  async updatePaymentStatus(externalOrderId: string, status: 'PAID' | 'FAILED', gatewayReference?: string): Promise<boolean> {
    if (this.isSandbox) {
      return true;
    }

    if (!this.axiosClient) return false;

    try {
      const isPaid = status === 'PAID';
      const updatePayload: Record<string, any> = {
        status: isPaid ? 'processing' : 'failed',
      };

      if (isPaid && gatewayReference) {
        updatePayload.transaction_id = gatewayReference;
      }

      await this.axiosClient.put(this.getRequestUrl(`orders/${externalOrderId}`), updatePayload);
      return true;
    } catch {
      return false;
    }
  }

  async fetchOrder(externalOrderId: string): Promise<UniversalOrder> {
    if (this.isSandbox) {
      return {
        externalOrderId,
        orderNumber: '9999',
        customerName: 'Sandbox Customer',
        customerPhone: '+263771234567',
        totalAmount: 120.0,
        currency: 'USD',
        items: [],
      };
    }

    if (!this.axiosClient) {
      throw new Error('WooCommerce API client is not configured');
    }

    try {
      const response = await this.axiosClient.get(this.getRequestUrl(`orders/${externalOrderId}`));
      const o = response.data;

      return {
        externalOrderId: String(o.id),
        orderNumber: String(o.number),
        customerName: `${o.billing?.first_name || ''} ${o.billing?.last_name || ''}`.trim() || 'WhatsApp Customer',
        customerPhone: o.billing?.phone || '',
        deliveryAddress: o.billing?.address_1 || '',
        totalAmount: parseFloat(o.total || '0'),
        currency: o.currency || 'USD',
        items: o.line_items.map((li: any) => ({
          externalProductId: String(li.product_id),
          externalVariantId: li.variation_id ? String(li.variation_id) : undefined,
          productName: li.name,
          quantity: li.quantity,
          unitPrice: parseFloat(li.price || '0'),
          lineTotal: parseFloat(li.total || '0'),
        })),
      };
    } catch (err: any) {
      throw new Error(`Failed to fetch WooCommerce order: ${err.message}`);
    }
  }

  async updateStock(externalProductId: string, quantity: number, externalVariantId?: string): Promise<boolean> {
    if (this.isSandbox) {
      return true;
    }

    if (!this.axiosClient) return false;

    try {
      if (externalVariantId) {
        await this.axiosClient.put(
          this.getRequestUrl(`products/${externalProductId}/variations/${externalVariantId}`),
          {
            manage_stock: true,
            stock_quantity: quantity,
          }
        );
      } else {
        await this.axiosClient.put(this.getRequestUrl(`products/${externalProductId}`), {
          manage_stock: true,
          stock_quantity: quantity,
        });
      }
      return true;
    } catch {
      return false;
    }
  }

  async registerWebhooks(deliveryUrl: string): Promise<boolean> {
    if (this.isSandbox) {
      console.log('[WooCommerce Webhook] Running in sandbox mode. Webhooks will not be registered.');
      return true;
    }

    if (!this.axiosClient) {
      console.warn('[WooCommerce Webhook] API client is not configured.');
      return false;
    }

    try {
      // 1. Fetch existing webhooks to avoid duplicates or to delete outdated webhooks
      const existingResponse = await this.axiosClient.get(this.getRequestUrl('webhooks'), {
        params: { per_page: 100 }
      });
      const webhooks = existingResponse.data || [];

      // Clean up existing webhooks matching our name/delivery_url prefix if the URL changed
      for (const w of webhooks) {
        if (w.name?.includes('WhatsApp Commerce Hub') && w.delivery_url !== deliveryUrl) {
          try {
            await this.axiosClient.delete(this.getRequestUrl(`webhooks/${w.id}`), {
              params: { force: true }
            });
            console.log(`[WooCommerce Webhook] Deleted outdated webhook: ${w.id} (${w.delivery_url})`);
          } catch (deleteErr: any) {
            console.warn(`[WooCommerce Webhook] Failed to delete webhook ${w.id}:`, deleteErr.message);
          }
        }
      }

      // Re-fetch remaining webhooks after cleanup
      const remainingResponse = await this.axiosClient.get(this.getRequestUrl('webhooks'), {
        params: { per_page: 100 }
      });
      const remainingWebhooks = remainingResponse.data || [];

      const hasCreated = remainingWebhooks.some(
        (w: any) => w.delivery_url === deliveryUrl && w.topic === 'order.created'
      );
      const hasUpdated = remainingWebhooks.some(
        (w: any) => w.delivery_url === deliveryUrl && w.topic === 'order.updated'
      );

      if (!hasCreated) {
        await this.axiosClient.post(this.getRequestUrl('webhooks'), {
          name: 'WhatsApp Commerce Hub - Order Created',
          topic: 'order.created',
          delivery_url: deliveryUrl,
          status: 'active',
        });
        console.log('[WooCommerce Webhook] Registered order.created webhook successfully.');
      } else {
        console.log('[WooCommerce Webhook] order.created webhook already registered.');
      }

      if (!hasUpdated) {
        await this.axiosClient.post(this.getRequestUrl('webhooks'), {
          name: 'WhatsApp Commerce Hub - Order Updated',
          topic: 'order.updated',
          delivery_url: deliveryUrl,
          status: 'active',
        });
        console.log('[WooCommerce Webhook] Registered order.updated webhook successfully.');
      } else {
        console.log('[WooCommerce Webhook] order.updated webhook already registered.');
      }

      return true;
    } catch (err: any) {
      console.error('[WooCommerce Webhook] Failed to register WooCommerce webhooks:', err.response?.data || err.message);
      return false;
    }
  }

  private getMockProducts(): UniversalProduct[] {
    return [
      {
        externalId: 'p_headphones',
        name: 'AeroSound Pro Wireless Headphones',
        description: 'Experience premium high-fidelity audio with active noise cancelling (ANC), 40-hour battery life, and ultra-comfortable memory foam earcups.\n\nCategories: Electronics, Audio Devices',
        sku: 'AS-PRO-WH',
        price: 99.99,
        currency: 'USD',
        stockQuantity: 15,
        stockStatus: 'instock',
        imageUrl: 'https://images.unsplash.com/photo-1505740420928-5e560c06d30e?w=500&auto=format&fit=crop&q=60',
        variants: [],
      },
      {
        externalId: 'p_smartwatch',
        name: 'KronoSync Smart Active Watch',
        description: 'Track your health, workouts, and sleep. Features an AMOLED display, built-in GPS, heart rate monitor, and 10 days of battery life.\n\nCategories: Electronics, Wearables',
        sku: 'KS-ACT-SW',
        price: 149.50,
        currency: 'USD',
        stockQuantity: 8,
        stockStatus: 'instock',
        imageUrl: 'https://images.unsplash.com/photo-1523275335684-37898b6baf30?w=500&auto=format&fit=crop&q=60',
        variants: [
          {
            externalId: 'v_smartwatch_black',
            name: 'KronoSync Smart Active Watch - Space Black',
            sku: 'KS-ACT-SW-BLK',
            price: 149.50,
            stockQuantity: 5,
            stockStatus: 'instock',
            attributes: { Color: 'Space Black' },
          },
          {
            externalId: 'v_smartwatch_silver',
            name: 'KronoSync Smart Active Watch - Silver Steel',
            sku: 'KS-ACT-SW-SLV',
            price: 159.50,
            stockQuantity: 3,
            stockStatus: 'instock',
            attributes: { Color: 'Silver Steel' },
          },
        ],
      },
      {
        externalId: 'p_speaker',
        name: 'VibeBeam Mini Waterproof Speaker',
        description: 'Compact size with powerful punchy bass. IPX7 waterproof rating makes it perfect for beach, pool, or outdoor camping. Supports stereo pairing.\n\nCategories: Electronics, Audio Devices',
        sku: 'VB-MINI-SP',
        price: 39.99,
        currency: 'USD',
        stockQuantity: 30,
        stockStatus: 'instock',
        imageUrl: 'https://images.unsplash.com/photo-1608043152269-423dbba4e7e1?w=500&auto=format&fit=crop&q=60',
        variants: [],
      },
      {
        externalId: 'p_wallet',
        name: 'AeroSlim Minimalist Leather Wallet',
        description: 'Handcrafted genuine top-grain leather wallet with RFID blocking security. Holds up to 10 cards and cash in a sleek, front-pocket friendly design.\n\nCategories: Accessories',
        sku: 'AS-MIN-LW',
        price: 24.99,
        currency: 'USD',
        stockQuantity: 4,
        stockStatus: 'instock',
        imageUrl: 'https://images.unsplash.com/photo-1627124765111-1a23f53835e5?w=500&auto=format&fit=crop&q=60',
        variants: [],
      },
      {
        externalId: 'p_charger',
        name: 'VoltCharge 65W GaN Fast Charger',
        description: 'High-speed charging for laptops, tablets, and smartphones. Dual USB-C and one USB-A ports, compact foldable plug design.\n\nCategories: Accessories',
        sku: 'VC-65W-GAN',
        price: 29.99,
        currency: 'USD',
        stockQuantity: 0,
        stockStatus: 'outofstock',
        imageUrl: 'https://images.unsplash.com/photo-1622445262465-2481c4574875?w=500&auto=format&fit=crop&q=60',
        variants: [],
      },
    ];
  }
}
