import { serve } from 'https://deno.land/std@0.168.0/http/server.ts'
import { createClient } from 'https://esm.sh/@supabase/supabase-js@2'
import { createHmac } from 'https://deno.land/std@0.168.0/node/crypto.ts'
import { wrapHandler, logError } from '../_shared/error-handler.ts'
import { createScraperClient } from '../_shared/scraper-client.ts'

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

// Generate OAuth 1.0a signature
function generateOAuthSignature(
  method: string,
  url: string,
  params: Record<string, string>,
  consumerSecret: string = '',
  tokenSecret: string = ''
): string {
  // Sort parameters
  const sortedParams = Object.keys(params)
    .sort()
    .map(key => `${encodeURIComponent(key)}=${encodeURIComponent(params[key])}`)
    .join('&')

  // Create signature base string
  const signatureBaseString = [
    method.toUpperCase(),
    encodeURIComponent(url),
    encodeURIComponent(sortedParams)
  ].join('&')

  // Create signing key
  const signingKey = `${encodeURIComponent(consumerSecret)}&${encodeURIComponent(tokenSecret)}`

  // Generate signature
  const signature = createHmac('sha256', signingKey)
    .update(signatureBaseString)
    .digest('base64')

  return signature
}

// Validate store URL
function validateStoreUrl(storeUrl: string): { valid: boolean; error?: string; normalized?: string } {
  try {
    // Remove trailing slash
    let normalized = storeUrl.trim().replace(/\/$/, '')

    // Add https:// if missing
    if (!normalized.startsWith('http://') && !normalized.startsWith('https://')) {
      normalized = `https://${normalized}`
    }

    // Parse URL
    const url = new URL(normalized)

    // Must be HTTPS for security
    if (url.protocol !== 'https:') {
      return { valid: false, error: 'Store URL must use HTTPS' }
    }

    return { valid: true, normalized }
  } catch (error) {
    return { valid: false, error: 'Invalid store URL format' }
  }
}

// Register store with scraper service
async function registerStoreWithScraper(
  storeId: string,
  storeUrl: string,
  supabase: any
): Promise<void> {
  try {
    console.log(`[WooCommerce] Registering store ${storeId} with scraper service`)

    // Create scraper client with global configuration
    const scraperClient = await createScraperClient()

    // Register shop with scraper using store_id as custom_id
    const job = await scraperClient.registerShop(storeUrl, storeId)
    console.log(`[WooCommerce] Scraper registration job created: ${job.id}`)

    // Set up webhook to receive scraper status updates
    const webhookUrl = `${Deno.env.get('SUPABASE_URL')}/functions/v1/scraper-webhook`
    try {
      await scraperClient.setWebhook(storeId, webhookUrl)
      console.log(`[WooCommerce] Scraper webhook configured for store ${storeId}`)
    } catch (webhookError) {
      console.warn(`[WooCommerce] Failed to configure scraper webhook:`, webhookError)
      // Continue anyway - webhook is optional
    }

    // Enable scheduled scraping
    try {
      await scraperClient.setScheduling(storeId, true)
      console.log(`[WooCommerce] Scraper scheduling enabled for store ${storeId}`)
    } catch (scheduleError) {
      console.warn(`[WooCommerce] Failed to enable scraper scheduling:`, scheduleError)
      // Continue anyway
    }

    // Update database to mark as registered
    const { error: updateError } = await supabase
      .from('stores')
      .update({ scraper_registered: true })
      .eq('id', storeId)

    if (updateError) {
      console.error(`[WooCommerce] Failed to update scraper registration status:`, updateError)
      // Continue anyway - this is not critical for the OAuth flow
    } else {
      console.log(`[WooCommerce] Store ${storeId} successfully registered with scraper`)
    }

  } catch (error) {
    console.error(`[WooCommerce] Failed to register store with scraper:`, error)
    // Don't throw error - scraper registration should not fail the OAuth flow
  }
}

// Test WooCommerce API connection
async function testWooCommerceConnection(
  storeUrl: string,
  consumerKey: string,
  consumerSecret: string
): Promise<{ success: boolean; error?: string; data?: any }> {
  try {
    // Test with system status endpoint
    const testUrl = `${storeUrl}/wp-json/wc/v3/system_status`

    const oauthParams: Record<string, string> = {
      oauth_consumer_key: consumerKey,
      oauth_timestamp: Math.floor(Date.now() / 1000).toString(),
      oauth_nonce: crypto.randomUUID().replace(/-/g, ''),
      oauth_signature_method: 'HMAC-SHA256'
    }

    // Generate signature
    const signature = generateOAuthSignature('GET', testUrl, oauthParams, consumerSecret)
    oauthParams.oauth_signature = signature

    // Build authorization header
    const authHeader = 'OAuth ' + Object.keys(oauthParams)
      .map(key => `${key}="${encodeURIComponent(oauthParams[key])}"`)
      .join(', ')

    const response = await fetch(testUrl, {
      method: 'GET',
      headers: {
        'Authorization': authHeader,
        'Accept': 'application/json'
      }
    })

    if (!response.ok) {
      const errorText = await response.text()
      console.error('[WooCommerce] API test failed:', response.status, errorText)
      return {
        success: false,
        error: `API connection failed (${response.status}): ${errorText.substring(0, 100)}`
      }
    }

    const data = await response.json()
    return { success: true, data }
  } catch (error) {
    console.error('[WooCommerce] Connection test error:', error)
    return {
      success: false,
      error: error instanceof Error ? error.message : 'Failed to connect to WooCommerce store'
    }
  }
}

serve(wrapHandler('oauth-woocommerce', async (req) => {
  if (req.method === 'OPTIONS') {
    return new Response('ok', { headers: corsHeaders })
  }
    const url = new URL(req.url)
    const action = url.searchParams.get('action')

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

    // Handle manual API key connection
    if (action === 'connect_manual') {
      const { storeUrl: storeUrlParam, consumerKey, consumerSecret, phoneNumberId } = await req.json()

      if (!storeUrlParam || !consumerKey || !consumerSecret) {
        return new Response(
          JSON.stringify({ error: 'storeUrl, consumerKey, and consumerSecret are required' }),
          { status: 400, headers: { ...corsHeaders, 'Content-Type': 'application/json' } }
        )
      }

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

      // Validate store URL
      const validation = validateStoreUrl(storeUrlParam)
      if (!validation.valid) {
        return new Response(
          JSON.stringify({ error: validation.error }),
          { status: 400, headers: { ...corsHeaders, 'Content-Type': 'application/json' } }
        )
      }

      // 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 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' } }
        )
      }

      // Test API connection
      const testResult = await testWooCommerceConnection(
        validation.normalized!,
        consumerKey,
        consumerSecret
      )

      if (!testResult.success) {
        console.error('[WooCommerce] API connection test failed:', testResult.error)
        return new Response(
          JSON.stringify({
            error: testResult.error || 'Failed to connect to WooCommerce store'
          }),
          { status: 400, headers: { ...corsHeaders, 'Content-Type': 'application/json' } }
        )
      }

      // Extract store info from API response
      const systemStatus = testResult.data
      const wcVersion = systemStatus?.environment?.version || 'unknown'
      const wpVersion = systemStatus?.environment?.wp_version || 'unknown'
      const storeName = systemStatus?.settings?.site_title?.value || new URL(validation.normalized!).hostname

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

      // Verify phone number is available and belongs to user's country
      const { data: phoneNumber, error: phoneError } = await supabaseAdmin
        .from('phone_numbers')
        .select('*')
        .eq('id', phoneNumberId)
        .eq('is_available', true)
        .eq('is_active', true)
        .is('assigned_to_store_id', null)
        .single()

      if (phoneError || !phoneNumber) {
        console.error('[WooCommerce] Phone number validation failed:', phoneError)
        return new Response(
          JSON.stringify({ error: 'Selected phone number is not available' }),
          { status: 400, headers: { ...corsHeaders, 'Content-Type': 'application/json' } }
        )
      }

      // Store credentials in database
      const { data: insertedStore, error: insertError } = await supabaseAdmin
        .from('stores')
        .insert({
          user_id: user.id,
          platform_name: 'woocommerce',
          store_name: storeName,
          store_url: validation.normalized,
          api_key: consumerKey,
          api_secret: consumerSecret,
          phone_number_id: phoneNumberId,
          scopes: ['read'],
          alt_data: {
            wcVersion,
            wpVersion,
            apiVersion: 'wc/v3',
            connectedAt: new Date().toISOString(),
            authMethod: 'manual'
          }
        })
        .select('id')
        .single()

      if (insertError || !insertedStore) {
        console.error('[WooCommerce] Error storing credentials:', insertError)
        return new Response(
          JSON.stringify({ error: 'Failed to save store credentials' }),
          { status: 500, headers: { ...corsHeaders, 'Content-Type': 'application/json' } }
        )
      }

      // Assign phone number to store
      const { error: phoneUpdateError } = await supabaseAdmin
        .from('phone_numbers')
        .update({
          assigned_to_store_id: insertedStore.id,
          assigned_to_user_id: user.id,
          is_available: false,
          assigned_at: new Date().toISOString(),
          updated_at: new Date().toISOString()
        })
        .eq('id', phoneNumberId)

      if (phoneUpdateError) {
        console.error('[WooCommerce] Error assigning phone number:', phoneUpdateError)
        // Delete the store since phone assignment failed
        await supabaseAdmin.from('stores').delete().eq('id', insertedStore.id)
        return new Response(
          JSON.stringify({ error: 'Failed to assign phone number to store' }),
          { status: 500, headers: { ...corsHeaders, 'Content-Type': 'application/json' } }
        )
      }

      console.log(`[WooCommerce] Store connected successfully (manual): ${storeName}`)

      // Register store with scraper service in background
      registerStoreWithScraper(insertedStore.id, validation.normalized, supabaseAdmin)
        .then(() => console.log(`[WooCommerce] Scraper registration completed for store ${insertedStore.id}`))
        .catch(err => console.error(`[WooCommerce] Scraper registration failed:`, err))

      // Trigger auto-sync in background
      const triggerSyncUrl = `${supabaseUrl}/functions/v1/trigger-sync`
      fetch(triggerSyncUrl, {
        method: 'POST',
        headers: {
          'Authorization': `Bearer ${supabaseServiceKey}`,
          'Content-Type': 'application/json'
        },
        body: JSON.stringify({ store_id: insertedStore.id })
      })
        .then(() => console.log(`[WooCommerce] Auto-sync triggered for store ${insertedStore.id}`))
        .catch(err => console.error(`[WooCommerce] Failed to trigger auto-sync:`, err))

      return new Response(
        JSON.stringify({
          success: true,
          message: 'Store connected successfully',
          storeName
        }),
        { status: 200, headers: { ...corsHeaders, 'Content-Type': 'application/json' } }
      )
    }

    // Unknown action
    return new Response(
      JSON.stringify({ error: 'Invalid action parameter' }),
      { status: 400, headers: { ...corsHeaders, 'Content-Type': 'application/json' } }
    )
}))
