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 { createHmac, timingSafeEqual } from 'https://deno.land/std@0.168.0/node/crypto.ts'

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

// Validate HMAC signature from ShopRenter
function validateHMAC(query: Record<string, string>, clientSecret: string): boolean {
  const { hmac, ...params } = query

  if (!hmac) {
    console.error('[ShopRenter] HMAC missing from request')
    return false
  }

  // Build sorted query string without HMAC
  const sortedParams = Object.keys(params)
    .sort()
    .map(key => `${key}=${params[key]}`)
    .join('&')

  // Calculate HMAC using sha256
  const calculatedHmac = createHmac('sha256', clientSecret)
    .update(sortedParams)
    .digest('hex')

  // Timing-safe comparison
  try {
    return timingSafeEqual(
      new TextEncoder().encode(calculatedHmac),
      new TextEncoder().encode(hmac)
    )
  } catch (error) {
    console.error('[ShopRenter] HMAC comparison error:', error)
    return false
  }
}

// Validate timestamp to prevent replay attacks
function validateTimestamp(timestamp: string, maxAgeSeconds = 300): boolean {
  const requestTime = parseInt(timestamp, 10)
  const currentTime = Math.floor(Date.now() / 1000)
  const age = currentTime - requestTime

  if (age < 0) {
    console.error('[ShopRenter] Request timestamp is in the future')
    return false
  }

  if (age > maxAgeSeconds) {
    console.error(`[ShopRenter] Request timestamp too old: ${age}s > ${maxAgeSeconds}s`)
    return false
  }

  return true
}

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

  try {
    const url = new URL(req.url)
    const shopname = url.searchParams.get('shopname')
    const code = url.searchParams.get('code')
    const timestamp = url.searchParams.get('timestamp')
    const hmac = url.searchParams.get('hmac')

    console.log(`[ShopRenter] Uninstall webhook received for ${shopname}`)

    // Check required parameters
    if (!shopname || !timestamp || !hmac) {
      return new Response(
        JSON.stringify({ message: 'Missing required parameters' }),
        { status: 200, headers: { ...corsHeaders, 'Content-Type': 'application/json' } }
      )
    }

    // Get environment variables
    const shoprenterClientSecret = Deno.env.get('SHOPRENTER_APP_CLIENT_SECRET')
    const supabaseUrl = Deno.env.get('SUPABASE_URL')!
    const supabaseServiceKey = Deno.env.get('SUPABASE_SERVICE_ROLE_KEY')!

    if (!shoprenterClientSecret) {
      console.error('SHOPRENTER_APP_CLIENT_SECRET not configured')
      // Still return 200 to prevent retries
      return new Response(
        JSON.stringify({ message: 'Configuration error' }),
        { status: 200, headers: { ...corsHeaders, 'Content-Type': 'application/json' } }
      )
    }

    // Validate timestamp
    if (!validateTimestamp(timestamp)) {
      console.error('[ShopRenter] Timestamp validation failed')
      // Still return 200 to prevent retries
      return new Response(
        JSON.stringify({ message: 'Timestamp invalid' }),
        { status: 200, headers: { ...corsHeaders, 'Content-Type': 'application/json' } }
      )
    }

    // Validate HMAC
    const queryParams: Record<string, string> = {
      shopname,
      timestamp,
      hmac
    }
    if (code) {
      queryParams.code = code
    }

    if (!validateHMAC(queryParams, shoprenterClientSecret)) {
      console.error('[ShopRenter] HMAC validation failed')
      // Still return 200 to prevent retries
      return new Response(
        JSON.stringify({ message: 'HMAC validation failed' }),
        { status: 200, headers: { ...corsHeaders, 'Content-Type': 'application/json' } }
      )
    }

    // Create Supabase client with service role key
    const supabase = createClient(supabaseUrl, supabaseServiceKey)

    // Find store by shopname
    const { data: store, error: storeError } = await supabase
      .from('stores')
      .select('id')
      .eq('platform_name', 'shoprenter')
      .eq('store_name', shopname)
      .maybeSingle()

    if (storeError) {
      console.error('[ShopRenter] Error finding store:', storeError)
      // Still return 200
      return new Response(
        JSON.stringify({ message: 'Store lookup error' }),
        { status: 200, headers: { ...corsHeaders, 'Content-Type': 'application/json' } }
      )
    }

    if (store) {
      // Deactivate store
      const { error: updateError } = await supabase
        .from('stores')
        .update({
          alt_data: { uninstalled: true, uninstalled_at: new Date().toISOString() }
        })
        .eq('id', store.id)

      if (updateError) {
        console.error('[ShopRenter] Error updating store:', updateError)
      }

      // Delete associated data
      // Delete cached products
      await supabase
        .from('shoprenter_products_cache')
        .delete()
        .eq('store_id', store.id)

      // Delete webhooks
      await supabase
        .from('shoprenter_webhooks')
        .delete()
        .eq('store_id', store.id)

      console.log(`[ShopRenter] Store ${shopname} uninstalled successfully`)
    } else {
      console.log(`[ShopRenter] Store ${shopname} not found in database`)
    }

    // Always respond with 200 (ShopRenter expects this)
    return new Response(
      JSON.stringify({ message: 'Uninstall processed' }),
      { status: 200, headers: { ...corsHeaders, 'Content-Type': 'application/json' } }
    )

  } catch (error) {
    console.error('[ShopRenter] Uninstall webhook error:', error)
    // Still return 200 to prevent retries
    return new Response(
      JSON.stringify({ message: 'Internal error' }),
      { status: 200, headers: { ...corsHeaders, 'Content-Type': 'application/json' } }
    )
  }
}))
