import { serve } from 'https://deno.land/std@0.168.0/http/server.ts'
import { createClient } from 'https://esm.sh/@supabase/supabase-js@2'
import { wrapHandler, logError } from '../_shared/error-handler.ts'
import {
  fetchProducts,
  fetchOrders,
  fetchCustomers,
  WooCommerceProduct,
  WooCommerceOrder,
  WooCommerceCustomer
} from '../_shared/woocommerce-client.ts'
import { formatFirstValidPhone, detectCountryCode } from '../_shared/phone-formatter.ts'
import {
  collectionExists,
  createCollection,
  upsertPoints,
  deletePointsByFilter,
  scrollPoints,
  getCollectionName,
  generatePointId,
  initializeStoreCollections,
  generateEmbeddingBatch,
  createProductText,
  createOrderText,
  createCustomerText,
  QdrantPoint
} from '../_shared/qdrant-client.ts'

const corsHeaders = {
  'Access-Control-Allow-Origin': '*',
  'Access-Control-Allow-Headers': 'authorization, x-client-info, apikey, content-type',
}

// Rate limiter class to prevent API throttling
class RateLimiter {
  private queue: Array<() => Promise<any>> = []
  private running = 0
  private maxConcurrent = 5
  private delayMs = 200 // 5 requests per second

  async add<T>(fn: () => Promise<T>): Promise<T> {
    while (this.running >= this.maxConcurrent) {
      await new Promise(resolve => setTimeout(resolve, this.delayMs))
    }

    this.running++
    try {
      const result = await fn()
      await new Promise(resolve => setTimeout(resolve, this.delayMs))
      return result
    } finally {
      this.running--
    }
  }
}

// Retry logic for API calls
async function fetchWithRetry<T>(
  fn: () => Promise<T>,
  maxRetries = 3,
  retryDelay = 1000
): Promise<T> {
  for (let i = 0; i < maxRetries; i++) {
    try {
      return await fn()
    } catch (error: any) {
      const isLastAttempt = i === maxRetries - 1

      // Check if error is rate limiting
      if (error.message?.includes('429') || error.message?.includes('Rate limit')) {
        if (!isLastAttempt) {
          const delay = retryDelay * Math.pow(2, i) // Exponential backoff
          console.log(`[WooCommerce] Rate limited, retrying in ${delay}ms...`)
          await new Promise(resolve => setTimeout(resolve, delay))
          continue
        }
      }

      // For other errors or last attempt, throw
      if (isLastAttempt) {
        throw error
      }

      // Retry other errors with shorter delay
      await new Promise(resolve => setTimeout(resolve, retryDelay))
    }
  }

  throw new Error('Max retries exceeded')
}

// Log Qdrant sync operation
async function logQdrantSync(
  supabaseAdmin: any,
  storeId: string,
  syncType: string,
  collectionName: string,
  operation: string,
  itemsProcessed: number,
  itemsSucceeded: number,
  itemsFailed: number,
  startedAt: Date,
  errorMessage?: string
): Promise<void> {
  try {
    await supabaseAdmin
      .from('qdrant_sync_logs')
      .insert({
        store_id: storeId,
        sync_type: syncType,
        collection_name: collectionName,
        operation,
        items_processed: itemsProcessed,
        items_succeeded: itemsSucceeded,
        items_failed: itemsFailed,
        error_message: errorMessage,
        started_at: startedAt.toISOString(),
        completed_at: new Date().toISOString(),
      })
  } catch (error) {
    console.error('[Qdrant] Failed to log sync operation:', error)
  }
}

// Sync products to Qdrant
async function syncProductsToQdrant(
  storeId: string,
  storeName: string,
  products: WooCommerceProduct[],
  supabaseAdmin: any
): Promise<{ synced: number; errors: number; skipped?: number }> {
  const startTime = new Date()
  const collectionName = getCollectionName(storeName, 'products')

  console.log(`[Qdrant] Syncing ${products.length} products to ${collectionName}`)

  let synced = 0
  let errors = 0
  let skipped = 0

  try {
    if (!(await collectionExists(collectionName))) {
      await createCollection(collectionName, [
        { field: 'store_id', type: 'keyword' },
        { field: 'product_id', type: 'keyword' },
        { field: 'platform', type: 'keyword' },
        { field: 'stock_status', type: 'keyword' },
        { field: 'price', type: 'float' },
        { field: 'sku', type: 'keyword' },
      ])
    }

    // Get existing product IDs from Qdrant to detect deletions and changes
    const existingPoints = await scrollPoints(collectionName, {
      must: [{ key: 'store_id', match: { value: storeId } }]
    }, 1000)

    const existingProductIds = new Set(
      existingPoints.points.map((p: any) => p.payload?.product_id).filter(Boolean)
    )

    // Create a map of existing products with their synced_at timestamps
    const existingProductMap = new Map(
      existingPoints.points.map((p: any) => [
        p.payload?.product_id,
        p.payload?.synced_at
      ])
    )

    const currentProductIds = new Set(products.map(p => p.id.toString()))

    // Find deleted products
    const deletedProductIds = Array.from(existingProductIds).filter(
      id => !currentProductIds.has(id)
    )

    // Delete removed products from Qdrant
    if (deletedProductIds.length > 0) {
      console.log(`[Qdrant] Deleting ${deletedProductIds.length} removed products`)
      await deletePointsByFilter(collectionName, {
        must: [
          { key: 'store_id', match: { value: storeId } },
          { key: 'product_id', match: { any: deletedProductIds } }
        ]
      })
    }

    // Get SQL cache data to detect changes (check raw_data hashes)
    const { data: cachedProducts } = await supabaseAdmin
      .from('woocommerce_products_cache')
      .select('wc_product_id, raw_data, last_synced_at')
      .eq('store_id', storeId)
      .in('wc_product_id', products.map(p => p.id.toString()))

    const cachedProductMap = new Map(
      (cachedProducts || []).map((cp: any) => [cp.wc_product_id, cp])
    )

    // Filter products that need embedding updates (new or changed)
    const productsNeedingEmbeddings = products.filter((product) => {
      const productId = product.id.toString()
      const cached = cachedProductMap.get(productId)

      // If not in cache, it's new - needs embedding
      if (!cached) {
        return true
      }

      // Compare raw_data to detect changes (deep comparison)
      const currentHash = JSON.stringify(product)
      const cachedHash = JSON.stringify(cached.raw_data)

      if (currentHash !== cachedHash) {
        console.log(`[Qdrant] Product ${productId} has changed, regenerating embedding`)
        return true
      }

      // Product unchanged, skip embedding generation
      skipped++
      return false
    })

    console.log(`[Qdrant] ${productsNeedingEmbeddings.length} products need embeddings, ${skipped} unchanged`)

    // Generate text representations only for products that need updates
    const productTexts = productsNeedingEmbeddings.map((product) =>
      createProductText({
        name: product.name,
        description: product.description,
        short_description: product.short_description,
        sku: product.sku,
        categories: product.categories,
        tags: product.tags?.map((t: any) => t.name) || [],
        attributes: product.attributes,
        price: product.price,
        stock_status: product.stock_status,
      })
    )

    // Generate embeddings in batch (more efficient) - only for changed products
    let embeddings: number[][] = []
    if (productTexts.length > 0) {
      console.log(`[Qdrant] Generating embeddings for ${productTexts.length} products...`)
      embeddings = await generateEmbeddingBatch(productTexts)
      console.log(`[Qdrant] Embeddings generated successfully`)
    }

    // Convert only changed/new products to Qdrant points with embeddings
    const points: QdrantPoint[] = productsNeedingEmbeddings.map((product, index) => ({
      id: generatePointId('woocommerce', storeId, product.id),
      vector: embeddings[index],
      payload: {
        // Basic identification
        store_id: storeId,
        product_id: product.id.toString(),
        platform: 'woocommerce',
        name: product.name,
        sku: product.sku || null,

        // Pricing
        price: parseFloat(product.price) || 0,
        regular_price: product.regular_price ? parseFloat(product.regular_price) : null,
        sale_price: product.sale_price ? parseFloat(product.sale_price) : null,

        // Descriptions
        description: product.description || null,
        short_description: product.short_description || null,

        // Categorization
        categories: product.categories || [],
        tags: product.tags?.map((t: any) => ({ id: t.id, name: t.name, slug: t.slug })) || [],

        // Attributes and variations
        attributes: product.attributes || [],
        variations: product.variations || [],

        // Images
        images: product.images?.map((img: any) => ({
          id: img.id,
          src: img.src,
          alt: img.alt || product.name
        })) || [],

        // Stock information
        stock_status: product.stock_status,
        stock_quantity: product.stock_quantity,
        manage_stock: product.manage_stock || false,
        backorders: product.backorders || 'no',

        // Product type and status
        type: product.type || 'simple',
        status: product.status || 'publish',
        featured: product.featured || false,

        // Metadata
        permalink: product.permalink || null,
        synced_at: new Date().toISOString(),
      }
    }))

    // Only upsert if there are changed products
    if (points.length > 0) {
      await upsertPoints(collectionName, points)
      synced = points.length
    }

    await logQdrantSync(
      supabaseAdmin,
      storeId,
      'products',
      collectionName,
      'upsert',
      products.length,
      synced,
      errors,
      startTime
    )

    console.log(`[Qdrant] Products sync complete: ${synced} synced, ${skipped} skipped (unchanged), ${deletedProductIds.length} deleted`)
  } catch (error: any) {
    console.error('[Qdrant] Product sync error:', error)
    errors = products.length
    await logQdrantSync(
      supabaseAdmin,
      storeId,
      'products',
      collectionName,
      'upsert',
      products.length,
      synced,
      errors,
      startTime,
      error.message
    )
  }

  return { synced, errors, skipped }
}

// Sync orders to Qdrant
async function syncOrdersToQdrant(
  storeId: string,
  storeName: string,
  orders: WooCommerceOrder[],
  supabaseAdmin: any
): Promise<{ synced: number; errors: number }> {
  const startTime = new Date()
  const collectionName = getCollectionName(storeName, 'orders')

  console.log(`[Qdrant] Syncing ${orders.length} orders to ${collectionName}`)

  let synced = 0
  let errors = 0

  try {
    if (!(await collectionExists(collectionName))) {
      await createCollection(collectionName, [
        { field: 'store_id', type: 'keyword' },
        { field: 'order_id', type: 'keyword' },
        { field: 'platform', type: 'keyword' },
        { field: 'status', type: 'keyword' },
        { field: 'total', type: 'float' },
        { field: 'customer_email', type: 'keyword' },
      ])
    }

    // Generate text representations for all orders
    const orderTexts = orders.map((order) =>
      createOrderText({
        order_number: order.number || order.id,
        customer_name: `${order.billing?.first_name || ''} ${order.billing?.last_name || ''}`.trim(),
        customer_email: order.billing?.email,
        customer_phone: order.billing?.phone,
        billing_address: order.billing,
        shipping_address: order.shipping,
        total_price: order.total,
        total: order.total,
        currency: order.currency,
        status: order.status,
        financial_status: order.status,
        line_items: order.line_items,
        note: order.customer_note,
      })
    )

    // Generate embeddings in batch
    console.log(`[Qdrant] Generating embeddings for ${orderTexts.length} orders...`)
    const embeddings = await generateEmbeddingBatch(orderTexts)
    console.log(`[Qdrant] Embeddings generated successfully`)

    // Convert orders to Qdrant points with embeddings
    const points: QdrantPoint[] = orders.map((order, index) => ({
      id: generatePointId('woocommerce', storeId, order.id),
      vector: embeddings[index],
      payload: {
        store_id: storeId,
        order_id: order.id.toString(),
        platform: 'woocommerce',
        order_number: order.number || order.id.toString(),
        status: order.status,
        total: parseFloat(order.total) || 0,
        total_price: parseFloat(order.total) || 0,
        currency: order.currency || 'USD',
        customer_name: `${order.billing?.first_name || ''} ${order.billing?.last_name || ''}`.trim(),
        customer_email: order.billing?.email || null,
        customer_phone: order.billing?.phone || null,
        phone: order.billing?.phone || null,
        billing_address: order.billing || null,
        billing_city: order.billing?.city || null,
        billing_country: order.billing?.country || null,
        shipping_address: order.shipping || null,
        shipping_city: order.shipping?.city || null,
        shipping_country: order.shipping?.country || null,
        note: order.customer_note || null,
        synced_at: new Date().toISOString(),
      }
    }))

    await upsertPoints(collectionName, points)
    synced = points.length

    await logQdrantSync(
      supabaseAdmin,
      storeId,
      'orders',
      collectionName,
      'upsert',
      orders.length,
      synced,
      errors,
      startTime
    )

    console.log(`[Qdrant] Orders sync complete: ${synced} synced`)
  } catch (error: any) {
    console.error('[Qdrant] Order sync error:', error)
    errors = orders.length
    await logQdrantSync(
      supabaseAdmin,
      storeId,
      'orders',
      collectionName,
      'upsert',
      orders.length,
      synced,
      errors,
      startTime,
      error.message
    )
  }

  return { synced, errors }
}

// Sync customers to Qdrant
async function syncCustomersToQdrant(
  storeId: string,
  storeName: string,
  customers: WooCommerceCustomer[],
  supabaseAdmin: any
): Promise<{ synced: number; errors: number }> {
  const startTime = new Date()
  const collectionName = getCollectionName(storeName, 'customers')

  console.log(`[Qdrant] Syncing ${customers.length} customers to ${collectionName}`)

  let synced = 0
  let errors = 0

  try {
    if (!(await collectionExists(collectionName))) {
      await createCollection(collectionName, [
        { field: 'store_id', type: 'keyword' },
        { field: 'customer_id', type: 'keyword' },
        { field: 'platform', type: 'keyword' },
        { field: 'email', type: 'keyword' },
      ])
    }

    // Generate text representations for all customers
    const customerTexts = customers.map((customer) =>
      createCustomerText({
        first_name: customer.first_name,
        last_name: customer.last_name,
        username: customer.username,
        email: customer.email,
        phone: customer.billing?.phone,
        billing: customer.billing,
        shipping: customer.shipping,
        orders_count: customer.orders_count,
        total_spent: customer.total_spent,
      })
    )

    // Generate embeddings in batch
    console.log(`[Qdrant] Generating embeddings for ${customerTexts.length} customers...`)
    const embeddings = await generateEmbeddingBatch(customerTexts)
    console.log(`[Qdrant] Embeddings generated successfully`)

    // Convert customers to Qdrant points with embeddings
    const points: QdrantPoint[] = customers.map((customer, index) => ({
      id: generatePointId('woocommerce', storeId, customer.id),
      vector: embeddings[index],
      payload: {
        store_id: storeId,
        customer_id: customer.id.toString(),
        platform: 'woocommerce',
        email: customer.email || null,
        first_name: customer.first_name || null,
        last_name: customer.last_name || null,
        username: customer.username || null,
        phone: customer.billing?.phone || customer.shipping?.phone || null,
        billing_address: customer.billing || null,
        shipping_address: customer.shipping || null,
        city: customer.billing?.city || customer.shipping?.city || null,
        country: customer.billing?.country || customer.shipping?.country || null,
        orders_count: customer.orders_count || 0,
        total_spent: parseFloat(customer.total_spent || '0'),
        synced_at: new Date().toISOString(),
      }
    }))

    await upsertPoints(collectionName, points)
    synced = points.length

    await logQdrantSync(
      supabaseAdmin,
      storeId,
      'customers',
      collectionName,
      'upsert',
      customers.length,
      synced,
      errors,
      startTime
    )

    console.log(`[Qdrant] Customers sync complete: ${synced} synced`)
  } catch (error: any) {
    console.error('[Qdrant] Customer sync error:', error)
    errors = customers.length
    await logQdrantSync(
      supabaseAdmin,
      storeId,
      'customers',
      collectionName,
      'upsert',
      customers.length,
      synced,
      errors,
      startTime,
      error.message
    )
  }

  return { synced, errors }
}

// Sync products from WooCommerce
async function syncProducts(
  storeId: string,
  storeName: string,
  supabaseAdmin: any,
  rateLimiter: RateLimiter,
  qdrantEnabled: boolean,
  canSyncProducts: boolean
): Promise<{ synced: number; errors: number; errorMessage?: string; qdrant?: { synced: number; errors: number } }> {
  console.log('[WooCommerce] Syncing products...')
  let synced = 0
  let errors = 0
  let page = 1
  const perPage = 25
  const allProducts: WooCommerceProduct[] = []
  const allProductsToCache: any[] = []

  if (!canSyncProducts) {
    console.log('[WooCommerce] Product sync disabled by store permissions')
    return { synced: 0, errors: 0 }
  }

  try {
    while (true) {
      const products = await rateLimiter.add(() =>
        fetchWithRetry(() => fetchProducts(storeId, page, perPage))
      )

      if (!products || products.length === 0) {
        break
      }

      // Collect all products for Qdrant sync
      allProducts.push(...products)

      // Map and upsert products to SQL cache with exclusion status
      const productsToCache = await Promise.all(
        products.map(async (product: WooCommerceProduct) => {
          // Check if product is excluded by category using database function
          const { data: categoryExcluded, error: categoryExclusionError } = await supabaseAdmin
            .rpc('is_product_excluded_by_category', {
              p_store_id: storeId,
              p_categories: product.categories || [],
              p_platform: 'woocommerce'
            })

          if (categoryExclusionError) {
            console.error(`[WooCommerce] Error checking category exclusion for product ${product.id}:`, categoryExclusionError)
          }

          // Check if product is individually excluded from cache
          const { data: existingProduct, error: existingError } = await supabaseAdmin
            .from('woocommerce_products_cache')
            .select('excluded')
            .eq('store_id', storeId)
            .eq('product_id', product.id.toString())
            .single()

          if (existingError && existingError.code !== 'PGRST116') {
            console.error(`[WooCommerce] Error checking existing product exclusion for ${product.id}:`, existingError)
          }

          // Product is excluded if:
          // 1. Excluded by category, OR
          // 2. Individually excluded (from existing cache record)
          const isExcluded = categoryExcluded || (existingProduct?.excluded === true)

          return {
            store_id: storeId,
            product_id: product.id.toString(),
            name: product.name,
            sku: product.sku || null,
            categories: product.categories || [],
            excluded: isExcluded,
            last_synced_at: new Date().toISOString()
          }
        })
      )

      // Collect products for exclusion tracking
      allProductsToCache.push(...productsToCache)

      const { error: upsertError } = await supabaseAdmin
        .from('woocommerce_products_cache')
        .upsert(productsToCache, {
          onConflict: 'store_id,product_id'
        })

      if (upsertError) {
        console.error('[WooCommerce] Error caching products:', upsertError)
        errors += productsToCache.length
      } else {
        synced += productsToCache.length
        console.log(`[WooCommerce] Cached ${productsToCache.length} products (page ${page})`)
      }

      // Check if there are more pages
      if (products.length < perPage) {
        break
      }

      page++
    }

    console.log(`[WooCommerce] Products sync complete: ${synced} synced, ${errors} errors`)

    // Handle Qdrant sync with exclusion logic
    let qdrantResult
    if (qdrantEnabled && allProducts.length > 0) {
      // Get excluded product IDs for Qdrant cleanup
      const excludedProductIds = allProductsToCache
        .filter(p => p.excluded)
        .map(p => p.product_id)

      // Filter products for Qdrant sync (only non-excluded)
      const productsForQdrant = allProducts.filter(product => {
        const productCacheItem = allProductsToCache.find(p => p.product_id === product.id.toString())
        return productCacheItem && !productCacheItem.excluded
      })

      // Delete excluded products from Qdrant
      if (excludedProductIds.length > 0) {
        console.log(`[WooCommerce] Deleting ${excludedProductIds.length} excluded products from Qdrant...`)
        try {
          const { deletePointsByFilter, getCollectionName } = await import('../_shared/qdrant-client.ts')
          const collectionName = getCollectionName(storeName, 'products')
          await deletePointsByFilter(
            collectionName,
            {
              key: 'product_id',
              match: { any: excludedProductIds }
            }
          )
          console.log(`[WooCommerce] Deleted excluded products from Qdrant successfully`)
        } catch (qdrantDeleteError) {
          console.error('[WooCommerce] Error deleting excluded products from Qdrant:', qdrantDeleteError)
        }
      }

      // Sync remaining (non-excluded) products to Qdrant
      qdrantResult = await syncProductsToQdrant(storeId, storeName, productsForQdrant, supabaseAdmin)
      console.log(`[WooCommerce] Qdrant sync complete: ${qdrantResult.synced} synced, ${qdrantResult.errors} errors, ${excludedProductIds.length} excluded`)
    }

    return { synced, errors, qdrant: qdrantResult }
  } catch (error) {
    const errorMessage = error instanceof Error ? error.message : 'Unknown error'
    console.error('[WooCommerce] Product sync error:', errorMessage, error)
    errors++
    return { synced, errors, errorMessage }
  }
}

// Sync orders from WooCommerce (Qdrant only - no SQL cache per GDPR compliance)
async function syncOrders(
  storeId: string,
  storeName: string,
  supabaseAdmin: any,
  rateLimiter: RateLimiter,
  countryCode: string,
  qdrantEnabled: boolean,
  canSyncOrders: boolean
): Promise<{ synced: number; errors: number; errorMessage?: string; qdrant?: { synced: number; errors: number } }> {
  console.log('[WooCommerce] Syncing orders (Qdrant only - no SQL cache per GDPR)...')
  let synced = 0
  let errors = 0
  let page = 1
  const perPage = 25
  const allOrders: WooCommerceOrder[] = []

  if (!canSyncOrders) {
    console.log('[WooCommerce] Order sync disabled by store permissions')
    return { synced: 0, errors: 0 }
  }

  try {
    while (true) {
      const orders = await rateLimiter.add(() =>
        fetchWithRetry(() => fetchOrders(storeId, page, perPage))
      )

      if (!orders || orders.length === 0) {
        break
      }

      // Collect all orders for Qdrant sync
      allOrders.push(...orders)
      synced += orders.length
      console.log(`[WooCommerce] Fetched ${orders.length} orders (page ${page}) for Qdrant sync`)

      // Check if there are more pages
      if (orders.length < perPage) {
        break
      }

      page++
    }

    console.log(`[WooCommerce] Orders fetch complete: ${synced} fetched, ${errors} errors`)

    // Sync to Qdrant if enabled (GDPR-compliant: vector database only, no SQL cache)
    let qdrantResult
    if (qdrantEnabled && allOrders.length > 0) {
      qdrantResult = await syncOrdersToQdrant(storeId, storeName, allOrders, supabaseAdmin)
    }

    return { synced, errors, qdrant: qdrantResult }
  } catch (error) {
    const errorMessage = error instanceof Error ? error.message : 'Unknown error'
    console.error('[WooCommerce] Order sync error:', errorMessage, error)
    errors++
    return { synced, errors, errorMessage }
  }
}

// Sync customers from WooCommerce (Qdrant only - no SQL cache per GDPR compliance)
async function syncCustomers(
  storeId: string,
  storeName: string,
  supabaseAdmin: any,
  rateLimiter: RateLimiter,
  countryCode: string,
  qdrantEnabled: boolean,
  canSyncCustomers: boolean
): Promise<{ synced: number; errors: number; errorMessage?: string; qdrant?: { synced: number; errors: number } }> {
  console.log('[WooCommerce] Syncing customers (Qdrant only - no SQL cache per GDPR)...')
  let synced = 0
  let errors = 0
  let page = 1
  const perPage = 25
  const allCustomers: WooCommerceCustomer[] = []

  if (!canSyncCustomers) {
    console.log('[WooCommerce] Customer sync disabled by store permissions')
    return { synced: 0, errors: 0 }
  }

  try {
    while (true) {
      const customers = await rateLimiter.add(() =>
        fetchWithRetry(() => fetchCustomers(storeId, page, perPage))
      )

      if (!customers || customers.length === 0) {
        break
      }

      // Collect all customers for Qdrant sync
      allCustomers.push(...customers)
      synced += customers.length
      console.log(`[WooCommerce] Fetched ${customers.length} customers (page ${page}) for Qdrant sync`)

      // Check if there are more pages
      if (customers.length < perPage) {
        break
      }

      page++
    }

    console.log(`[WooCommerce] Customers fetch complete: ${synced} fetched, ${errors} errors`)

    // Sync to Qdrant if enabled (GDPR-compliant: vector database only, no SQL cache)
    let qdrantResult
    if (qdrantEnabled && allCustomers.length > 0) {
      qdrantResult = await syncCustomersToQdrant(storeId, storeName, allCustomers, supabaseAdmin)
    }

    return { synced, errors, qdrant: qdrantResult }
  } catch (error) {
    const errorMessage = error instanceof Error ? error.message : 'Unknown error'
    console.error('[WooCommerce] Customer sync error:', errorMessage, error)
    errors++
    return { synced, errors, errorMessage }
  }
}

serve(wrapHandler('woocommerce-sync', async (req) => {
  if (req.method === 'OPTIONS') {
    return new Response('ok', { headers: corsHeaders })
  }

  try {
    const supabaseUrl = Deno.env.get('SUPABASE_URL')!
    const supabaseKey = Deno.env.get('SUPABASE_ANON_KEY')!
    const supabaseServiceKey = Deno.env.get('SUPABASE_SERVICE_ROLE_KEY')!

    const supabase = createClient(supabaseUrl, supabaseKey)
    const supabaseAdmin = createClient(supabaseUrl, supabaseServiceKey)

    // GET request - Get sync status
    if (req.method === 'GET') {
      // Get user from authorization header
      const authHeader = req.headers.get('authorization')
      if (!authHeader) {
        return new Response(
          JSON.stringify({ error: 'No authorization header' }),
          { status: 401, headers: { ...corsHeaders, 'Content-Type': 'application/json' } }
        )
      }

      const token = authHeader.replace('Bearer ', '')
      const { data: { user }, error: userError } = await supabase.auth.getUser(token)

      if (userError || !user) {
        return new Response(
          JSON.stringify({ error: 'Invalid token' }),
          { status: 401, headers: { ...corsHeaders, 'Content-Type': 'application/json' } }
        )
      }

      // Get storeId from query params
      const url = new URL(req.url)
      const storeId = url.searchParams.get('store_id')

      if (!storeId) {
        return new Response(
          JSON.stringify({ error: 'store_id parameter is required' }),
          { status: 400, headers: { ...corsHeaders, 'Content-Type': 'application/json' } }
        )
      }

      // Verify store belongs to user
      const { data: store, error: storeError } = await supabase
        .from('stores')
        .select('id')
        .eq('id', storeId)
        .eq('user_id', user.id)
        .eq('platform_name', 'woocommerce')
        .single()

      if (storeError || !store) {
        return new Response(
          JSON.stringify({ error: 'Store not found or access denied' }),
          { status: 404, headers: { ...corsHeaders, 'Content-Type': 'application/json' } }
        )
      }

      // Get sync status using helper function
      const { data: statusData, error: statusError } = await supabaseAdmin
        .rpc('get_woocommerce_sync_status', { p_store_id: storeId })

      if (statusError) {
        console.error('[WooCommerce] Error fetching sync status:', statusError)
        return new Response(
          JSON.stringify({ error: 'Failed to fetch sync status' }),
          { status: 500, headers: { ...corsHeaders, 'Content-Type': 'application/json' } }
        )
      }

      const status = statusData && statusData.length > 0 ? statusData[0] : {
        last_sync_at: null,
        sync_status: 'idle',
        products_count: 0,
        orders_count: 0,
        customers_count: 0
      }

      return new Response(
        JSON.stringify(status),
        { status: 200, headers: { ...corsHeaders, 'Content-Type': 'application/json' } }
      )
    }

    // POST request - Trigger sync
    if (req.method === 'POST') {
      // Parse request body first to check for internal_call flag
      const body = await req.json()
      const { store_id, sync_type, internal_call } = body

      let user = null

      // Handle authentication - skip for internal calls from trigger-sync
      if (internal_call !== true) {
        // Regular user authentication
        const authHeader = req.headers.get('authorization')
        if (!authHeader) {
          return new Response(
            JSON.stringify({ error: 'No authorization header' }),
            { status: 401, headers: { ...corsHeaders, 'Content-Type': 'application/json' } }
          )
        }

        const token = authHeader.replace('Bearer ', '')

        // Use the anon key client for user auth, not the service role client
        const { data: { user: authUser }, error: userError } = await supabase.auth.getUser(token)

        if (userError || !authUser) {
          console.error('[WooCommerce] User authentication failed:', userError)
          return new Response(
            JSON.stringify({ error: 'Invalid token' }),
            { status: 401, headers: { ...corsHeaders, 'Content-Type': 'application/json' } }
          )
        }

        user = authUser
      } else {
        console.log('[WooCommerce] Internal call detected, skipping user authentication')
      }

      if (!store_id) {
        return new Response(
          JSON.stringify({ error: 'store_id is required' }),
          { status: 400, headers: { ...corsHeaders, 'Content-Type': 'application/json' } }
        )
      }

      if (!sync_type || !['products', 'orders', 'customers', 'all'].includes(sync_type)) {
        return new Response(
          JSON.stringify({ error: 'sync_type must be one of: products, orders, customers, all' }),
          { status: 400, headers: { ...corsHeaders, 'Content-Type': 'application/json' } }
        )
      }

      // Verify store exists and optionally belongs to user (for non-internal calls)
      let storeQuery = supabaseAdmin
        .from('stores')
        .select('id, store_name, store_url, qdrant_sync_enabled')
        .eq('id', store_id)
        .eq('platform_name', 'woocommerce')

      // For non-internal calls, verify store belongs to user
      if (user) {
        storeQuery = storeQuery.eq('user_id', user.id)
      }

      const { data: store, error: storeError } = await storeQuery
        .single()

      if (storeError || !store) {
        return new Response(
          JSON.stringify({ error: 'Store not found or access denied' }),
          { status: 404, headers: { ...corsHeaders, 'Content-Type': 'application/json' } }
        )
      }

      // Get access policies from store_sync_config
      const { data: syncConfig } = await supabaseAdmin
        .from('store_sync_config')
        .select('products_access_policy, orders_access_policy, customers_access_policy')
        .eq('store_id', store_id)
        .single()

      // Only sync if policy is 'sync' (not 'api_only' or 'not_allowed')
      const canSyncProducts = syncConfig?.products_access_policy === 'sync'
      const canSyncOrders = syncConfig?.orders_access_policy === 'sync'
      const canSyncCustomers = syncConfig?.customers_access_policy === 'sync'
      const qdrantEnabled = store.qdrant_sync_enabled !== false

      console.log('[WooCommerce] Sync permissions:', {
        products: canSyncProducts,
        productsPolicy: syncConfig?.products_access_policy || 'not_configured',
        orders: canSyncOrders,
        ordersPolicy: syncConfig?.orders_access_policy || 'not_configured',
        customers: canSyncCustomers,
        customersPolicy: syncConfig?.customers_access_policy || 'not_configured',
        qdrant: qdrantEnabled
      })

      // Initialize Qdrant collections if enabled
      if (qdrantEnabled) {
        try {
          await initializeStoreCollections(
            store.store_name,
            canSyncOrders,
            canSyncCustomers
          )
        } catch (error) {
          console.error('[Qdrant] Failed to initialize collections:', error)
        }
      }

      // Detect country code from store URL for phone formatting
      const countryCode = detectCountryCode(store.store_url)
      console.log(`[WooCommerce] Detected country code: ${countryCode} for store: ${store.store_name}`)

      console.log(`[WooCommerce] Starting ${sync_type} sync for store ${store_id}`)

      const syncStats: any = {
        products: { synced: 0, errors: 0 },
        orders: { synced: 0, errors: 0 },
        customers: { synced: 0, errors: 0 }
      }

      const rateLimiter = new RateLimiter()

      // Sync based on type
      if (sync_type === 'products' || sync_type === 'all') {
        syncStats.products = await syncProducts(store_id, store.store_name, supabaseAdmin, rateLimiter, qdrantEnabled, canSyncProducts)
      }

      if (sync_type === 'orders' || sync_type === 'all') {
        syncStats.orders = await syncOrders(store_id, store.store_name, supabaseAdmin, rateLimiter, countryCode, qdrantEnabled, canSyncOrders)
      }

      if (sync_type === 'customers' || sync_type === 'all') {
        syncStats.customers = await syncCustomers(store_id, store.store_name, supabaseAdmin, rateLimiter, countryCode, qdrantEnabled, canSyncCustomers)
      }

      // Collect error messages for better diagnostics
      const errorMessages = []
      if (syncStats.products.errorMessage) errorMessages.push(`Products: ${syncStats.products.errorMessage}`)
      if (syncStats.orders.errorMessage) errorMessages.push(`Orders: ${syncStats.orders.errorMessage}`)
      if (syncStats.customers.errorMessage) errorMessages.push(`Customers: ${syncStats.customers.errorMessage}`)

      // Update store alt_data with sync info
      const { data: currentStore } = await supabaseAdmin
        .from('stores')
        .select('alt_data')
        .eq('id', store_id)
        .single()

      const altData = currentStore?.alt_data || {}

      await supabaseAdmin
        .from('stores')
        .update({
          alt_data: {
            ...altData,
            lastSync: new Date().toISOString(),
            syncStatus: 'completed',
            productsCount: syncStats.products.synced,
            ordersCount: syncStats.orders.synced,
            customersCount: syncStats.customers.synced,
            lastSyncStats: syncStats,
            lastSyncErrors: errorMessages.length > 0 ? errorMessages : undefined
          }
        })
        .eq('id', store_id)

      return new Response(
        JSON.stringify({
          success: true,
          message: `${sync_type} sync completed`,
          stats: syncStats,
          errorMessages: errorMessages.length > 0 ? errorMessages : undefined,
          timestamp: new Date().toISOString()
        }),
        { status: 200, headers: { ...corsHeaders, 'Content-Type': 'application/json' } }
      )
    }

    return new Response(
      JSON.stringify({ error: 'Method not allowed' }),
      { status: 405, headers: { ...corsHeaders, 'Content-Type': 'application/json' } }
    )

  } catch (error: any) {
    console.error('[WooCommerce] Error:', error)
    return new Response(
      JSON.stringify({
        success: false,
        error: error.message || 'An error occurred'
      }),
      { status: 500, headers: { ...corsHeaders, 'Content-Type': 'application/json' } }
    )
  }
}))
