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',
}

/**
 * Trigger sync for a newly registered store
 * This function initiates a background sync job for products, orders, and customers
 */
serve(wrapHandler('trigger-sync', async (req) => {
  if (req.method === 'OPTIONS') {
    return new Response('ok', { headers: corsHeaders })
  }

  try {
    const { store_id } = await req.json()

    if (!store_id) {
      return new Response(
        JSON.stringify({ error: 'store_id is required' }),
        { status: 400, 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 store details
    const { data: store, error: storeError } = await supabaseAdmin
      .from('stores')
      .select('id, platform_name, store_name, sync_status')
      .eq('id', store_id)
      .single()

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

    // Check if sync is already running
    if (store.sync_status === 'syncing') {
      console.log(`[TriggerSync] Sync already in progress for store ${store_id}`)
      return new Response(
        JSON.stringify({
          success: false,
          message: 'Sync already in progress',
          status: 'syncing'
        }),
        { status: 409, headers: { ...corsHeaders, 'Content-Type': 'application/json' } }
      )
    }

    console.log(`[TriggerSync] Starting sync for ${store.platform_name} store: ${store.store_name} (${store_id})`)

    // Mark sync as started
    await supabaseAdmin
      .from('stores')
      .update({
        sync_status: 'syncing',
        sync_started_at: new Date().toISOString(),
        sync_error: null
      })
      .eq('id', store_id)

    // Trigger appropriate sync based on platform
    let syncUrl: string
    let syncBody: any

    switch (store.platform_name) {
      case 'shopify':
        syncUrl = `${supabaseUrl}/functions/v1/shopify-sync?store_id=${store_id}`
        break
      case 'woocommerce':
        syncUrl = `${supabaseUrl}/functions/v1/woocommerce-sync`
        syncBody = {
          store_id,
          sync_type: 'all',
          internal_call: true
        }
        break
      case 'shoprenter':
        syncUrl = `${supabaseUrl}/functions/v1/shoprenter-sync/${store_id}`
        break
      default:
        console.error(`[TriggerSync] Unsupported platform: ${store.platform_name}`)
        await supabaseAdmin
          .from('stores')
          .update({
            sync_status: 'error',
            sync_error: `Unsupported platform: ${store.platform_name}`
          })
          .eq('id', store_id)

        return new Response(
          JSON.stringify({ error: `Unsupported platform: ${store.platform_name}` }),
          { status: 400, headers: { ...corsHeaders, 'Content-Type': 'application/json' } }
        )
    }

    // Trigger sync in background (don't wait for completion)
    fetch(syncUrl, {
      method: 'POST',
      headers: {
        'Authorization': `Bearer ${supabaseServiceKey}`,
        'Content-Type': 'application/json'
      },
      body: syncBody ? JSON.stringify(syncBody) : undefined
    })
      .then(async (response) => {
        const result = await response.json()

        if (response.ok) {
          console.log(`[TriggerSync] Sync completed successfully for ${store_id}`)

          // Extract sync statistics from result
          let syncStats = null
          if (result.stats) {
            // WooCommerce and ShopRenter format
            syncStats = result.stats
          } else if (result.results) {
            // Shopify format
            syncStats = {
              products: result.results.products || { synced: 0, errors: 0 },
              orders: result.results.orders || { synced: 0, errors: 0 },
              customers: result.results.customers || { synced: 0, errors: 0 }
            }
          }

          // Get current alt_data to preserve existing fields
          const { data: currentStore } = await supabaseAdmin
            .from('stores')
            .select('alt_data')
            .eq('id', store_id)
            .single()

          const altData = currentStore?.alt_data || {}
          const syncCompletedAt = new Date().toISOString()

          // Update stores table (runtime status only, preserve alt_data)
          await supabaseAdmin
            .from('stores')
            .update({
              sync_status: 'completed',
              alt_data: {
                ...altData,
                last_sync_at: syncCompletedAt,
                last_sync_stats: syncStats,
                last_sync_type: 'manual'
              },
              sync_error: null
            })
            .eq('id', store_id)

          // Update store_sync_config (single source of truth for sync timing)
          const { error: configUpdateError } = await supabaseAdmin
            .from('store_sync_config')
            .update({
              last_sync_at: syncCompletedAt
            })
            .eq('store_id', store_id)

          // If config doesn't exist, create it
          if (configUpdateError) {
            await supabaseAdmin
              .from('store_sync_config')
              .insert({
                store_id: store_id,
                enabled: true,
                sync_frequency: 'hourly',
                last_sync_at: syncCompletedAt
              })
          }
        } else {
          console.error(`[TriggerSync] Sync failed for ${store_id}:`, result)
          const errorTime = new Date().toISOString()
          await supabaseAdmin
            .from('stores')
            .update({
              sync_status: 'error',
              sync_error: result.error || 'Unknown error during sync'
            })
            .eq('id', store_id)

          // Update store_sync_config timestamp even on error (for retry logic)
          await supabaseAdmin
            .from('store_sync_config')
            .update({
              last_sync_at: errorTime
            })
            .eq('store_id', store_id)
        }
      })
      .catch(async (error) => {
        console.error(`[TriggerSync] Sync error for ${store_id}:`, error)
        const errorTime = new Date().toISOString()
        await supabaseAdmin
          .from('stores')
          .update({
            sync_status: 'error',
            sync_error: error.message || 'Unknown error during sync'
          })
          .eq('id', store_id)

        // Update store_sync_config timestamp even on error (for retry logic)
        await supabaseAdmin
          .from('store_sync_config')
          .update({
            last_sync_at: errorTime
          })
          .eq('store_id', store_id)
      })

    console.log(`[TriggerSync] Sync triggered successfully for ${store_id}`)

    return new Response(
      JSON.stringify({
        success: true,
        message: 'Sync triggered successfully',
        store_id,
        platform: store.platform_name,
        status: 'syncing'
      }),
      { status: 200, headers: { ...corsHeaders, 'Content-Type': 'application/json' } }
    )
  } catch (error) {
    logError('trigger-sync', error as Error, { store_id: req.json() })
    return new Response(
      JSON.stringify({ error: 'Internal server error' }),
      { status: 500, headers: { ...corsHeaders, 'Content-Type': 'application/json' } }
    )
  }
}))
