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'

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

/**
 * Scheduled Background Sync for WooCommerce Stores
 *
 * This Edge Function is designed to be called by pg_cron or external schedulers.
 * It requires an internal secret key for authentication instead of user tokens.
 *
 * Security: Uses INTERNAL_SYNC_SECRET environment variable for authentication
 */

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

  try {
    // Verify internal secret key for scheduled sync
    const internalSecret = req.headers.get('x-internal-secret')
    const expectedSecret = Deno.env.get('INTERNAL_SYNC_SECRET')

    if (!expectedSecret) {
      console.error('[WooCommerce Scheduled Sync] INTERNAL_SYNC_SECRET not configured')
      return new Response(
        JSON.stringify({ error: 'Service not configured' }),
        { status: 500, headers: { ...corsHeaders, 'Content-Type': 'application/json' } }
      )
    }

    if (!internalSecret || internalSecret !== expectedSecret) {
      console.warn('[WooCommerce Scheduled Sync] Invalid or missing internal secret')
      return new Response(
        JSON.stringify({ error: 'Unauthorized' }),
        { status: 401, headers: { ...corsHeaders, 'Content-Type': 'application/json' } }
      )
    }

    const supabaseUrl = Deno.env.get('SUPABASE_URL')!
    const supabaseServiceKey = Deno.env.get('SUPABASE_SERVICE_ROLE_KEY')!
    const supabaseAdmin = createClient(supabaseUrl, supabaseServiceKey)

    // Get sync frequency from request (set by pg_cron job)
    const body = await req.json().catch(() => ({}))
    const frequency = body.frequency || 'all' // Default to all frequencies

    // Get all active WooCommerce stores
    const { data: stores, error: storesError } = await supabaseAdmin
      .from('stores')
      .select(`
        id,
        user_id,
        store_name,
        store_url,
        alt_data
      `)
      .eq('platform_name', 'woocommerce')
      .eq('is_active', true)

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

    console.log(`[WooCommerce Scheduled Sync] Fetched ${stores?.length || 0} WooCommerce stores from database`)

    if (!stores || stores.length === 0) {
      console.log('[WooCommerce Scheduled Sync] No WooCommerce stores found')
      return new Response(
        JSON.stringify({
          success: true,
          message: 'No WooCommerce stores found',
          stores_processed: 0
        }),
        { status: 200, headers: { ...corsHeaders, 'Content-Type': 'application/json' } }
      )
    }

    // Get sync configs for all stores (including access policies)
    const storeIds = stores.map(s => s.id)
    const { data: syncConfigs, error: configError } = await supabaseAdmin
      .from('store_sync_config')
      .select('*')
      .in('store_id', storeIds)

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

    console.log(`[WooCommerce Scheduled Sync] Fetched ${syncConfigs?.length || 0} sync configs`)

    // Create a map of store_id -> config for easy lookup
    const configMap = new Map()
    syncConfigs?.forEach(config => {
      configMap.set(config.store_id, config)
    })

    // Filter stores that have sync enabled and are due for sync
    const now = new Date()
    const storesToSync = stores.filter(store => {
      const config = configMap.get(store.id)

      // Debug logging
      console.log(`[WooCommerce Scheduled Sync] Checking store ${store.id}:`, {
        has_config: !!config,
        enabled: config?.enabled,
        sync_frequency: config?.sync_frequency,
        next_sync_at: config?.next_sync_at,
        frequency_filter: frequency
      })

      if (!config || !config.enabled) {
        console.log(`[WooCommerce Scheduled Sync] Store ${store.id} filtered out: no config or disabled`)
        return false
      }

      // If specific frequency requested, filter by it
      if (frequency !== 'all' && config.sync_frequency !== frequency) {
        console.log(`[WooCommerce Scheduled Sync] Store ${store.id} filtered out: frequency mismatch (${config.sync_frequency} !== ${frequency})`)
        return false
      }

      // Check if sync is due
      if (config.next_sync_at) {
        const nextSync = new Date(config.next_sync_at)
        const isDue = nextSync <= now
        console.log(`[WooCommerce Scheduled Sync] Store ${store.id} next sync: ${config.next_sync_at}, is due: ${isDue}`)
        return isDue
      }

      // If no next_sync_at, sync is due
      console.log(`[WooCommerce Scheduled Sync] Store ${store.id} has no next_sync_at, sync is due`)
      return true
    })

    // Add config to store objects for later use
    storesToSync.forEach(store => {
      store.store_sync_config = configMap.get(store.id)
    })

    if (storesToSync.length === 0) {
      console.log('[WooCommerce Scheduled Sync] No WooCommerce stores due for sync')
      return new Response(
        JSON.stringify({
          success: true,
          message: 'No stores due for sync',
          stores_processed: 0,
          frequency: frequency
        }),
        { status: 200, headers: { ...corsHeaders, 'Content-Type': 'application/json' } }
      )
    }

    console.log(`[WooCommerce Scheduled Sync] Found ${storesToSync.length} stores due for sync`)

    const syncResults = []

    // Sync each store by calling the woocommerce-sync function
    for (const store of storesToSync) {
      const storeId = store.id
      const config = store.store_sync_config
      console.log(`[WooCommerce Scheduled Sync] Starting sync for store ${storeId} (${store.store_name})`)

      const syncStats = {
        store_id: storeId,
        store_name: store.store_name,
        products: { synced: 0, errors: 0 },
        customer_access_tested: false,
        order_access_tested: false,
        started_at: new Date().toISOString(),
        completed_at: null as string | null,
        status: 'success' as 'success' | 'partial' | 'failed',
        error_message: null as string | null
      }

      try {
        // Check access policies (GDPR compliance - Issue #95)
        const productsPolicy = config?.products_access_policy || 'sync'
        const ordersPolicy = config?.orders_access_policy || 'sync'
        const customersPolicy = config?.customers_access_policy || 'sync'

        console.log(`[WooCommerce Scheduled Sync] Store ${storeId} access policies:`, {
          products: productsPolicy,
          orders: ordersPolicy,
          customers: customersPolicy
        })

        // Skip sync if products policy doesn't allow sync
        if (productsPolicy !== 'sync') {
          console.log(`[WooCommerce Scheduled Sync] Products sync skipped for store ${storeId}: access policy is '${productsPolicy}' (requires 'sync')`)
          syncStats.status = 'success'
          syncStats.error_message = `Sync skipped: products access policy is '${productsPolicy}'`
          syncStats.completed_at = new Date().toISOString()
          syncResults.push(syncStats)

          // Still update sync timestamp
          const syncCompletedAt = new Date().toISOString()
          await supabaseAdmin
            .from('store_sync_config')
            .update({
              last_sync_at: syncCompletedAt,
            })
            .eq('store_id', storeId)

          continue // Skip to next store
        }

        // Only sync products now (GDPR compliance - Issue #48, enhanced in #95)
        // Customer and order data are accessed in real-time via webshop-data-api
        const syncType = 'products'

        // Call woocommerce-sync Edge Function (only if policy allows)
        const syncResponse = await fetch(`${supabaseUrl}/functions/v1/woocommerce-sync`, {
          method: 'POST',
          headers: {
            'Authorization': `Bearer ${supabaseServiceKey}`,
            'Content-Type': 'application/json'
          },
          body: JSON.stringify({
            store_id: storeId,
            sync_type: syncType,
            internal_call: true // Flag to bypass user auth
          })
        })

        if (!syncResponse.ok) {
          throw new Error(`Sync failed with status ${syncResponse.status}`)
        }

        const syncResult = await syncResponse.json()

        if (syncResult.success && syncResult.stats) {
          syncStats.products = syncResult.stats.products || { synced: 0, errors: 0 }

          // Determine status based on errors
          const hasErrors = syncStats.products.errors > 0
          syncStats.status = hasErrors ? 'partial' : 'success'

          // Report access policy status (for logging/monitoring)
          syncStats.customer_access_policy = config.customers_access_policy || 'not_configured'
          syncStats.order_access_policy = config.orders_access_policy || 'not_configured'
          syncStats.product_access_policy = config.products_access_policy || 'not_configured'
        } else {
          syncStats.status = 'failed'
          syncStats.error_message = syncResult.error || 'Unknown error'
        }

        // Update stores table status and store_sync_config timestamps
        const syncCompletedAt = new Date().toISOString()

        // Update stores table (runtime status only, no timestamps)
        await supabaseAdmin
          .from('stores')
          .update({
            sync_status: syncStats.status === 'success' ? 'completed' : 'error',
            sync_error: syncStats.error_message
          })
          .eq('id', storeId)

        // Update store_sync_config (single source of truth for sync timing)
        if (config) {
          await supabaseAdmin
            .from('store_sync_config')
            .update({
              last_sync_at: syncCompletedAt,
              // next_sync_at will be auto-calculated by trigger
            })
            .eq('store_id', storeId)
        } else {
          // Create sync config if it doesn't exist
          await supabaseAdmin
            .from('store_sync_config')
            .insert({
              store_id: storeId,
              enabled: true,
              sync_frequency: 'hourly',
              last_sync_at: syncCompletedAt
            })
        }

        syncStats.completed_at = new Date().toISOString()
        console.log(`[WooCommerce Scheduled Sync] Store ${storeId} sync completed with status: ${syncStats.status}`)

      } catch (error) {
        console.error(`[WooCommerce Scheduled Sync] Fatal error syncing store ${storeId}:`, error)
        syncStats.status = 'failed'
        syncStats.error_message = error.message
        syncStats.completed_at = new Date().toISOString()
      }

      syncResults.push(syncStats)
    }

    // Log sync summary to database
    try {
      await supabaseAdmin
        .from('sync_logs')
        .insert({
          sync_type: 'scheduled',
          platform: 'woocommerce',
          stores_processed: storesToSync.length,
          results: syncResults,
          started_at: syncResults[0]?.started_at || new Date().toISOString(),
          completed_at: new Date().toISOString()
        })
    } catch (error) {
      console.error('[WooCommerce Scheduled Sync] Failed to log sync results:', error)
      // Don't fail the request if logging fails
    }

    const successCount = syncResults.filter(r => r.status === 'success').length
    const partialCount = syncResults.filter(r => r.status === 'partial').length
    const failedCount = syncResults.filter(r => r.status === 'failed').length

    console.log(`[WooCommerce Scheduled Sync] Batch complete: ${successCount} success, ${partialCount} partial, ${failedCount} failed`)

    return new Response(
      JSON.stringify({
        success: true,
        message: 'Scheduled sync completed',
        summary: {
          stores_processed: storesToSync.length,
          success: successCount,
          partial: partialCount,
          failed: failedCount
        },
        results: syncResults,
        timestamp: new Date().toISOString()
      }),
      { status: 200, headers: { ...corsHeaders, 'Content-Type': 'application/json' } }
    )

  } catch (error) {
    console.error('[WooCommerce Scheduled Sync] Fatal error:', error)
    return new Response(
      JSON.stringify({
        success: false,
        error: 'Internal server error',
        message: error.message
      }),
      { status: 500, headers: { ...corsHeaders, 'Content-Type': 'application/json' } }
    )
  }
}))
