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 } from '../_shared/shoprenter-client.ts'

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

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

  try {
    // 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 supabaseUrl = Deno.env.get('SUPABASE_URL')!
    const supabaseKey = Deno.env.get('SUPABASE_ANON_KEY')!
    const supabase = createClient(supabaseUrl, supabaseKey)

    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 URL path
    const url = new URL(req.url)
    const pathParts = url.pathname.split('/')
    const storeId = pathParts[pathParts.length - 1]

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

    // Get pagination parameters
    const page = parseInt(url.searchParams.get('page') || '1')
    const limit = parseInt(url.searchParams.get('limit') || '25')
    const useCache = url.searchParams.get('cache') !== 'false'

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

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

    // Try to get from cache first
    if (useCache) {
      const { data: cachedProducts, error: cacheError } = await supabase
        .from('shoprenter_products_cache')
        .select('*')
        .eq('store_id', storeId)
        .order('created_at', { ascending: false })
        .range((page - 1) * limit, page * limit - 1)

      if (!cacheError && cachedProducts && cachedProducts.length > 0) {
        // Check if cache is fresh (less than 1 hour old)
        const latestSync = new Date(cachedProducts[0].last_synced_at).getTime()
        const now = Date.now()
        const cacheAge = now - latestSync

        if (cacheAge < 60 * 60 * 1000) { // 1 hour
          console.log(`[ShopRenter] Returning cached products for store ${storeId}`)

          // Get total count
          const { count } = await supabase
            .from('shoprenter_products_cache')
            .select('*', { count: 'exact', head: true })
            .eq('store_id', storeId)

          return new Response(
            JSON.stringify({
              success: true,
              source: 'cache',
              products: cachedProducts,
              pagination: {
                page,
                limit,
                total: count || 0
              }
            }),
            { status: 200, headers: { ...corsHeaders, 'Content-Type': 'application/json' } }
          )
        }
      }
    }

    // Fetch from ShopRenter API
    console.log(`[ShopRenter] Fetching products from API for store ${storeId}`)
    const productsData = await fetchProducts(storeId, page, limit)

    // Cache the products
    if (productsData.items && productsData.items.length > 0) {
      const supabaseServiceKey = Deno.env.get('SUPABASE_SERVICE_ROLE_KEY')!
      const supabaseAdmin = createClient(supabaseUrl, supabaseServiceKey)

      const productsToCache = productsData.items.map((product: any) => ({
        store_id: storeId,
        shoprenter_product_id: product.id,
        name: product.name,
        sku: product.sku,
        price: parseFloat(product.price) || 0,
        currency: product.currency || 'HUF',
        description: product.description,
        stock: product.stock,
        active: product.active !== false,
        raw_data: product,
        last_synced_at: new Date().toISOString()
      }))

      // Upsert products to cache
      const { error: upsertError } = await supabaseAdmin
        .from('shoprenter_products_cache')
        .upsert(productsToCache, {
          onConflict: 'store_id,shoprenter_product_id'
        })

      if (upsertError) {
        console.error('[ShopRenter] Error caching products:', upsertError)
      } else {
        console.log(`[ShopRenter] Cached ${productsToCache.length} products`)
      }
    }

    return new Response(
      JSON.stringify({
        success: true,
        source: 'api',
        products: productsData.items || [],
        pagination: productsData.pagination || {
          page,
          limit,
          total: productsData.items?.length || 0
        }
      }),
      { status: 200, headers: { ...corsHeaders, 'Content-Type': 'application/json' } }
    )
  } catch (error) {
    console.error('[ShopRenter Products] Error:', error)
    return new Response(
      JSON.stringify({
        error: error instanceof Error ? error.message : 'Unknown error occurred',
        success: false
      }),
      { status: 500, headers: { ...corsHeaders, 'Content-Type': 'application/json' } }
    )
  }
}))
