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 } 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, x-shopify-hmac-sha256, x-shopify-shop-domain, x-shopify-topic',
}

// Verify Shopify webhook HMAC signature
function verifyWebhookHmac(body: string, hmac: string, secret: string): boolean {
  try {
    const calculatedHmac = createHmac('sha256', secret)
      .update(body)
      .digest('base64')

    return calculatedHmac === hmac
  } catch (error) {
    console.error('[Shopify Webhook] HMAC verification error:', error)
    return false
  }
}

// Handle customers/data_request webhook
async function handleCustomersDataRequest(
  supabase: any,
  shopDomain: string,
  payload: any
): Promise<{ success: boolean; error?: string }> {
  try {
    console.log(`[Shopify GDPR] Customers data request for shop: ${shopDomain}`)

    // Find the store
    const { data: store, error: storeError } = await supabase
      .from('stores')
      .select('*')
      .eq('platform_name', 'shopify')
      .eq('store_url', shopDomain)
      .single()

    if (storeError || !store) {
      console.error('[Shopify GDPR] Store not found:', shopDomain)
      return { success: false, error: 'Store not found' }
    }

    // Log the GDPR request
    const { error: insertError } = await supabase
      .from('gdpr_requests')
      .insert({
        store_id: store.id,
        request_type: 'data_request',
        customer_id: payload.customer?.id?.toString(),
        shop_domain: shopDomain,
        request_payload: payload,
        status: 'pending'
      })

    if (insertError) {
      console.error('[Shopify GDPR] Error logging data request:', insertError)
      return { success: false, error: 'Failed to log data request' }
    }

    // Query customer data from our cache
    const { data: customerData, error: customerError } = await supabase
      .from('shopify_customers_cache')
      .select('*')
      .eq('store_id', store.id)
      .eq('shopify_customer_id', payload.customer?.id?.toString())
      .maybeSingle()

    // Query customer orders
    const { data: orderData, error: orderError } = await supabase
      .from('shopify_orders_cache')
      .select('*')
      .eq('store_id', store.id)
      .eq('customer_email', payload.customer?.email)

    // Prepare response data
    const responseData = {
      customer: customerData || payload.customer,
      orders: orderData || [],
      data_requested_at: new Date().toISOString(),
      note: 'This is all customer data stored by ShopCall.ai'
    }

    console.log(`[Shopify GDPR] Data request processed for customer: ${payload.customer?.id}`)

    // In production, you would:
    // 1. Send this data to the customer's email
    // 2. Or provide a secure download link
    // 3. Mark the request as completed after 30 days (Shopify requirement)

    return { success: true }
  } catch (error) {
    console.error('[Shopify GDPR] Error handling data request:', error)
    return {
      success: false,
      error: error instanceof Error ? error.message : 'Unknown error'
    }
  }
}

// Handle customers/redact webhook
async function handleCustomersRedact(
  supabase: any,
  shopDomain: string,
  payload: any
): Promise<{ success: boolean; error?: string }> {
  try {
    console.log(`[Shopify GDPR] Customers redact request for shop: ${shopDomain}`)

    // Find the store
    const { data: store, error: storeError } = await supabase
      .from('stores')
      .select('*')
      .eq('platform_name', 'shopify')
      .eq('store_url', shopDomain)
      .single()

    if (storeError || !store) {
      console.error('[Shopify GDPR] Store not found:', shopDomain)
      return { success: false, error: 'Store not found' }
    }

    // Log the GDPR request
    const { error: insertError } = await supabase
      .from('gdpr_requests')
      .insert({
        store_id: store.id,
        request_type: 'customer_redact',
        customer_id: payload.customer?.id?.toString(),
        shop_domain: shopDomain,
        request_payload: payload,
        status: 'processing'
      })

    if (insertError) {
      console.error('[Shopify GDPR] Error logging redact request:', insertError)
      return { success: false, error: 'Failed to log redact request' }
    }

    const customerId = payload.customer?.id?.toString()
    const customerEmail = payload.customer?.email

    // Delete customer data from cache
    const { error: deleteCustomerError } = await supabase
      .from('shopify_customers_cache')
      .delete()
      .eq('store_id', store.id)
      .eq('shopify_customer_id', customerId)

    if (deleteCustomerError) {
      console.error('[Shopify GDPR] Error deleting customer:', deleteCustomerError)
    }

    // Redact customer info from orders (keep order records but remove PII)
    const { error: updateOrdersError } = await supabase
      .from('shopify_orders_cache')
      .update({
        customer_name: '[REDACTED]',
        customer_email: '[REDACTED]',
        email: '[REDACTED]',
        phone: '[REDACTED]',
        billing_address: {},
        shipping_address: {},
        note: '[REDACTED]'
      })
      .eq('store_id', store.id)
      .eq('customer_email', customerEmail)

    if (updateOrdersError) {
      console.error('[Shopify GDPR] Error redacting orders:', updateOrdersError)
    }

    // Mark request as completed
    const { error: completeError } = await supabase
      .from('gdpr_requests')
      .update({
        status: 'completed',
        processed_at: new Date().toISOString()
      })
      .eq('store_id', store.id)
      .eq('request_type', 'customer_redact')
      .eq('customer_id', customerId)

    console.log(`[Shopify GDPR] Customer data redacted: ${customerId}`)

    return { success: true }
  } catch (error) {
    console.error('[Shopify GDPR] Error handling redact request:', error)
    return {
      success: false,
      error: error instanceof Error ? error.message : 'Unknown error'
    }
  }
}

// Handle shop/redact webhook
async function handleShopRedact(
  supabase: any,
  shopDomain: string,
  payload: any
): Promise<{ success: boolean; error?: string }> {
  try {
    console.log(`[Shopify GDPR] Shop redact request for shop: ${shopDomain}`)

    // Find the store
    const { data: store, error: storeError } = await supabase
      .from('stores')
      .select('*')
      .eq('platform_name', 'shopify')
      .eq('store_url', shopDomain)
      .single()

    if (storeError || !store) {
      console.error('[Shopify GDPR] Store not found:', shopDomain)
      // Even if store not found, return success (might have been deleted already)
      return { success: true }
    }

    // Log the GDPR request
    const { error: insertError } = await supabase
      .from('gdpr_requests')
      .insert({
        store_id: store.id,
        request_type: 'shop_redact',
        shop_domain: shopDomain,
        request_payload: payload,
        status: 'processing'
      })

    if (insertError) {
      console.error('[Shopify GDPR] Error logging shop redact request:', insertError)
    }

    // Delete all cached data for this store
    const tables = [
      'shopify_products_cache',
      'shopify_orders_cache',
      'shopify_customers_cache',
      'shopify_webhooks',
      'gdpr_requests'
    ]

    for (const table of tables) {
      const { error } = await supabase
        .from(table)
        .delete()
        .eq('store_id', store.id)

      if (error) {
        console.error(`[Shopify GDPR] Error deleting from ${table}:`, error)
      }
    }

    // Delete the store record itself
    const { error: deleteStoreError } = await supabase
      .from('stores')
      .delete()
      .eq('id', store.id)

    if (deleteStoreError) {
      console.error('[Shopify GDPR] Error deleting store:', deleteStoreError)
      return { success: false, error: 'Failed to delete store' }
    }

    console.log(`[Shopify GDPR] Shop data completely deleted: ${shopDomain}`)

    return { success: true }
  } catch (error) {
    console.error('[Shopify GDPR] Error handling shop redact:', error)
    return {
      success: false,
      error: error instanceof Error ? error.message : 'Unknown error'
    }
  }
}

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

  try {
    // Only accept POST requests for webhooks
    if (req.method !== 'POST') {
      return new Response(
        JSON.stringify({ error: 'Method not allowed' }),
        { status: 405, headers: { ...corsHeaders, 'Content-Type': 'application/json' } }
      )
    }

    // Get Shopify webhook headers
    const hmac = req.headers.get('x-shopify-hmac-sha256')
    const shopDomain = req.headers.get('x-shopify-shop-domain')
    const topic = req.headers.get('x-shopify-topic')

    console.log(`[Shopify Webhook] Received: ${topic} for shop: ${shopDomain}`)

    if (!hmac || !shopDomain || !topic) {
      console.error('[Shopify Webhook] Missing required headers')
      return new Response(
        JSON.stringify({ error: 'Missing required headers' }),
        { status: 400, headers: { ...corsHeaders, 'Content-Type': 'application/json' } }
      )
    }

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

    if (!shopifyApiSecret) {
      console.error('SHOPIFY_API_SECRET not configured')
      return new Response(
        JSON.stringify({ error: 'Server configuration error' }),
        { status: 500, headers: { ...corsHeaders, 'Content-Type': 'application/json' } }
      )
    }

    // Read request body
    const bodyText = await req.text()

    // Verify webhook HMAC
    if (!verifyWebhookHmac(bodyText, hmac, shopifyApiSecret)) {
      console.error('[Shopify Webhook] HMAC verification failed')
      return new Response(
        JSON.stringify({ error: 'Invalid webhook signature' }),
        { status: 401, headers: { ...corsHeaders, 'Content-Type': 'application/json' } }
      )
    }

    // Parse payload
    const payload = JSON.parse(bodyText)

    // Create Supabase admin client
    const supabase = createClient(supabaseUrl, supabaseServiceKey)

    // Route to appropriate handler based on topic
    let result: { success: boolean; error?: string }

    switch (topic) {
      case 'customers/data_request':
        result = await handleCustomersDataRequest(supabase, shopDomain, payload)
        break

      case 'customers/redact':
        result = await handleCustomersRedact(supabase, shopDomain, payload)
        break

      case 'shop/redact':
        result = await handleShopRedact(supabase, shopDomain, payload)
        break

      default:
        console.warn(`[Shopify Webhook] Unhandled topic: ${topic}`)
        // Return success for unknown topics (don't fail)
        result = { success: true }
    }

    if (!result.success) {
      console.error(`[Shopify Webhook] Handler failed for ${topic}:`, result.error)
      return new Response(
        JSON.stringify({ error: result.error || 'Processing failed' }),
        { status: 500, headers: { ...corsHeaders, 'Content-Type': 'application/json' } }
      )
    }

    // Return success response
    return new Response(
      JSON.stringify({ success: true, message: 'Webhook processed successfully' }),
      { status: 200, headers: { ...corsHeaders, 'Content-Type': 'application/json' } }
    )

  } catch (error) {
    logError('webhooks-shopify', error as Error, { method: req.method })
    return new Response(
      JSON.stringify({ error: 'Internal server error' }),
      { status: 500, headers: { ...corsHeaders, 'Content-Type': 'application/json' } }
    )
  }
}))

