import { db } from '@/db/client';
import { CatalogProductRecord } from '@/types';
import { resolveProductCategory } from './client';
import { cleanHtmlDescription, normalizeImageUrl } from '@/lib/meta/item-mapper';
import { syncCatalog } from '@/lib/sync/catalog-sync-service';
import { logger } from '@/lib/logger';

export async function processProductWebhook(
  shopId: string,
  topic: string,
  payload: any
): Promise<void> {
  const shop = await db.getShopById(shopId);
  if (!shop) {
    logger.warn(`[processProductWebhook] Shop #${shopId} not found`);
    return;
  }

  const rawId = payload?.id;
  if (!rawId) {
    logger.warn(`[processProductWebhook] Missing product ID in payload for topic ${topic}`);
    return;
  }

  const cleanProdId = String(rawId).replace(/^gid:\/\/shopify\/Product\//, '');
  const productGid = `gid://shopify/Product/${cleanProdId}`;

  if (topic === 'products/delete' || (payload.status && String(payload.status).toLowerCase() !== 'active')) {
    logger.info(`[processProductWebhook] Removing inactive/deleted product ${cleanProdId} from shop ${shop.shopify_domain}`);
    const existing = await db.getProductsByShopId(shopId);
    for (const p of existing) {
      if (p.shopify_product_id === productGid || p.shopify_product_id.includes(cleanProdId)) {
        await db.deleteProduct(p.id);
      }
    }
  } else if (topic === 'products/update' || topic === 'products/create') {
    const title = payload.title || 'Product';
    const bodyHtml = payload.body_html || payload.description || '';
    const description = cleanHtmlDescription(bodyHtml) || title;
    const vendor = payload.vendor || 'Store Brand';
    const productType = payload.product_type || '';
    const handle = payload.handle || title.toLowerCase().replace(/[^a-z0-9]+/g, '-');
    const tags = Array.isArray(payload.tags)
      ? payload.tags
      : typeof payload.tags === 'string'
      ? payload.tags.split(',').map((t: string) => t.trim())
      : [];

    const categories = resolveProductCategory(title, productType, tags);
    const mainImage = normalizeImageUrl(payload.image?.src || payload.images?.[0]?.src || '');
    const additionalImages = (payload.images || [])
      .slice(1)
      .map((img: any) => normalizeImageUrl(img?.src || img))
      .filter(Boolean);

    const variants = Array.isArray(payload.variants) && payload.variants.length > 0
      ? payload.variants
      : [
          {
            id: `${cleanProdId}_1`,
            title: 'Default Title',
            price: '0.00',
            sku: `SKU-${cleanProdId}`,
            inventory_quantity: 1,
          },
        ];

    const nowIso = new Date().toISOString();

    for (const v of variants) {
      const variantCleanId = String(v.id || `${cleanProdId}_1`).replace(/^gid:\/\/shopify\/ProductVariant\//, '');
      const variantGid = `gid://shopify/ProductVariant/${variantCleanId}`;
      const varTitle = v.title && v.title !== 'Default Title' ? v.title : null;
      const priceNum = parseFloat(v.price) || 0;
      const comparePriceNum = v.compare_at_price ? parseFloat(v.compare_at_price) : null;
      const sku = v.sku || `SKU-${variantCleanId}`;
      const matchedImg = v.image_id
        ? (payload.images?.find((img: any) => img.id === v.image_id)?.src || mainImage)
        : mainImage;
      const varImage = normalizeImageUrl(matchedImg) || mainImage || 'https://via.placeholder.com/600x600?text=No+Image';

      const isAvailable =
        v.available === true ||
        v.inventory_policy === 'continue' ||
        v.inventory_management === null ||
        (v.inventory_quantity !== undefined && v.inventory_quantity > 0);

      // Collect options if any
      const optionValues = [v.option1, v.option2, v.option3].filter(Boolean).join(' / ');

      const record: CatalogProductRecord = {
        id: `prod_${cleanProdId}_${variantCleanId}`,
        shop_id: shopId,
        shopify_product_id: productGid,
        shopify_variant_id: variantGid,
        meta_product_id: `FB_${cleanProdId}_${variantCleanId}`,
        sku,
        barcode: v.barcode || null,
        title,
        variant_title: varTitle,
        description,
        price: priceNum,
        compare_at_price: comparePriceNum,
        currency: 'USD',
        availability: isAvailable ? 'in stock' : 'out of stock',
        inventory_quantity: v.inventory_quantity ?? 0,
        image_url: varImage,
        additional_images: additionalImages,
        product_url: `https://${shop.shopify_domain}/products/${handle}?variant=${variantCleanId}`,
        google_product_category: categories.google_product_category,
        fb_product_category: categories.fb_product_category,
        brand: vendor,
        condition: 'new',
        custom_label_0: productType || undefined,
        custom_label_1: tags.slice(0, 3).join(', ') || undefined,
        custom_label_2: optionValues || undefined,
        status: 'synced',
        last_synced_at: nowIso,
      };

      await db.upsertProduct(record);
      logger.info(`[processProductWebhook] Upserted product variant ${record.id} (${title}) for shop ${shop.shopify_domain}`);
    }
  }

  // Trigger sync for any catalogs with auto_sync enabled or matching selection
  const catalogs = await db.getCatalogs(shopId);
  for (const cat of catalogs) {
    if (cat.auto_sync && cat.fb_catalog_id) {
      try {
        logger.info(`[processProductWebhook] Auto-syncing catalog ${cat.id} (${cat.fb_catalog_id}) following webhook update`);
        await syncCatalog(cat.id);
      } catch (catErr: any) {
        logger.warn(`[processProductWebhook] Auto-sync error for catalog ${cat.id}: ${catErr.message}`);
      }
    }
  }
}
