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

// Register store with scraper service
async function registerStoreWithScraper(
  storeId: string,
  storeUrl: string,
  supabase: any
): Promise<void> {
  try {
    console.log(`[ShopRenter] 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(`[ShopRenter] 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(`[ShopRenter] Scraper webhook configured for store ${storeId}`)
    } catch (webhookError) {
      console.warn(`[ShopRenter] Failed to configure scraper webhook:`, webhookError)
      // Continue anyway - webhook is optional
    }

    // Enable scheduled scraping
    try {
      await scraperClient.setScheduling(storeId, true)
      console.log(`[ShopRenter] Scraper scheduling enabled for store ${storeId}`)
    } catch (scheduleError) {
      console.warn(`[ShopRenter] 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(`[ShopRenter] Failed to update scraper registration status:`, updateError)
      // Continue anyway - this is not critical for the OAuth flow
    } else {
      console.log(`[ShopRenter] Store ${storeId} successfully registered with scraper`)
    }

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

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

  try {
    const supabaseUrl = Deno.env.get('SUPABASE_URL')!
    const supabaseServiceKey = Deno.env.get('SUPABASE_SERVICE_ROLE_KEY')!
    const supabase = createClient(supabaseUrl, supabaseServiceKey)

    // Get auth token from header
    const authHeader = req.headers.get('Authorization')
    if (!authHeader) {
      return new Response(
        JSON.stringify({ error: 'Authorization header required' }),
        { status: 401, headers: { ...corsHeaders, 'Content-Type': 'application/json' } }
      )
    }

    // Verify the user
    const token = authHeader.replace('Bearer ', '')
    const { data: { user }, error: authError } = await supabase.auth.getUser(token)

    if (authError || !user) {
      return new Response(
        JSON.stringify({ error: 'Invalid or expired token' }),
        { status: 401, headers: { ...corsHeaders, 'Content-Type': 'application/json' } }
      )
    }

    // Parse request body
    const body = await req.json()
    const { installation_id, phone_number_id } = body

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

    console.log(`[ShopRenter] Completing installation ${installation_id} for user ${user.id}`)

    // Fetch pending installation
    const { data: pendingInstall, error: fetchError } = await supabase
      .from('pending_shoprenter_installs')
      .select('*')
      .eq('installation_id', installation_id)
      .single()

    if (fetchError || !pendingInstall) {
      console.error('[ShopRenter] Pending installation not found:', fetchError)
      return new Response(
        JSON.stringify({ error: 'Installation not found or expired' }),
        { status: 404, headers: { ...corsHeaders, 'Content-Type': 'application/json' } }
      )
    }

    // Check if installation has expired
    if (new Date(pendingInstall.expires_at) < new Date()) {
      console.error('[ShopRenter] Installation has expired')
      // Clean up expired installation
      await supabase
        .from('pending_shoprenter_installs')
        .delete()
        .eq('id', pendingInstall.id)

      return new Response(
        JSON.stringify({ error: 'Installation has expired. Please try again.' }),
        { status: 410, headers: { ...corsHeaders, 'Content-Type': 'application/json' } }
      )
    }

    // Check if store already exists for this user with same shopname
    const { data: existingStore } = await supabase
      .from('stores')
      .select('id')
      .eq('user_id', user.id)
      .eq('platform_name', 'shoprenter')
      .eq('store_name', pendingInstall.shopname)
      .single()

    if (existingStore) {
      // Update existing store with new tokens
      const { error: updateError } = await supabase
        .from('stores')
        .update({
          access_token: pendingInstall.access_token,
          refresh_token: pendingInstall.refresh_token,
          token_expires_at: new Date(Date.now() + (pendingInstall.expires_in || 3600) * 1000).toISOString(),
          scopes: pendingInstall.scopes,
          is_active: true,
          updated_at: new Date().toISOString(),
          phone_number_id: pendingInstall.phone_number_id || existingStore.phone_number_id
        })
        .eq('id', existingStore.id)

      if (updateError) {
        console.error('[ShopRenter] Error updating existing store:', updateError)
        return new Response(
          JSON.stringify({ error: 'Failed to update store' }),
          { status: 500, headers: { ...corsHeaders, 'Content-Type': 'application/json' } }
        )
      }

      // Clean up pending installation
      await supabase
        .from('pending_shoprenter_installs')
        .delete()
        .eq('id', pendingInstall.id)

      console.log(`[ShopRenter] Updated existing store ${existingStore.id} for ${pendingInstall.shopname}`)

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

    // Get ShopRenter client credentials for alt_data
    const shoprenterClientId = Deno.env.get('SHOPRENTER_APP_CLIENT_ID') || Deno.env.get('SHOPRENTER_CLIENT_ID')
    const shoprenterClientSecret = Deno.env.get('SHOPRENTER_APP_CLIENT_SECRET') || Deno.env.get('SHOPRENTER_CLIENT_SECRET')

    // Use phone_number_id from request body if provided, otherwise fall back to pending installation
    const finalPhoneNumberId = phone_number_id || pendingInstall.phone_number_id

    // Create new store
    const { data: newStore, error: createError } = await supabase
      .from('stores')
      .insert({
        user_id: user.id,
        platform_name: 'shoprenter',
        store_name: pendingInstall.shopname,
        store_url: `https://${pendingInstall.shopname}.myshoprenter.hu`,
        access_token: pendingInstall.access_token,
        refresh_token: pendingInstall.refresh_token,
        token_expires_at: new Date(Date.now() + (pendingInstall.expires_in || 3600) * 1000).toISOString(),
        scopes: pendingInstall.scopes,
        is_active: true,
        phone_number_id: finalPhoneNumberId,
        alt_data: {
          client_id: shoprenterClientId,
          client_secret: shoprenterClientSecret,
          connectedAt: new Date().toISOString()
        }
      })
      .select()
      .single()

    if (createError || !newStore) {
      console.error('[ShopRenter] Error creating store:', createError)
      return new Response(
        JSON.stringify({ error: 'Failed to create store' }),
        { status: 500, headers: { ...corsHeaders, 'Content-Type': 'application/json' } }
      )
    }

    // Create default sync configuration
    const { error: syncConfigError } = await supabase
      .from('store_sync_config')
      .insert({
        store_id: newStore.id,
        enabled: true,
        sync_frequency: 'hourly',
        products_access_policy: 'sync',
        customers_access_policy: 'api_only',
        orders_access_policy: 'api_only'
      })

    if (syncConfigError) {
      console.error('[ShopRenter] Error creating sync config:', syncConfigError)
      // Non-fatal error, continue
    }

    // Update phone number assignment if provided
    if (finalPhoneNumberId) {
      const { error: phoneError } = await supabase
        .from('phone_numbers')
        .update({
          assigned_to_store_id: newStore.id,
          assigned_to_user_id: user.id,
          assigned_at: new Date().toISOString(),
          is_available: false
        })
        .eq('id', finalPhoneNumberId)

      if (phoneError) {
        console.error('[ShopRenter] Error updating phone number:', phoneError)
        // Non-fatal error, continue
      }
    }

    // Clean up pending installation
    await supabase
      .from('pending_shoprenter_installs')
      .delete()
      .eq('id', pendingInstall.id)

    // Clean up any related oauth_states
    await supabase
      .from('oauth_states')
      .delete()
      .eq('platform', 'shoprenter')
      .eq('shopname', pendingInstall.shopname)
      .eq('user_id', user.id)

    console.log(`[ShopRenter] Created new store ${newStore.id} for ${pendingInstall.shopname}`)

    // Register store with scraper service in background
    registerStoreWithScraper(newStore.id, `https://${pendingInstall.shopname}.myshoprenter.hu`, supabase)
      .then(() => console.log(`[ShopRenter] Scraper registration completed for store ${newStore.id}`))
      .catch(err => console.error(`[ShopRenter] Scraper registration failed:`, err))

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

  } catch (error) {
    console.error('[ShopRenter] Complete installation error:', error)
    return new Response(
      JSON.stringify({ error: 'Failed to complete installation' }),
      { status: 500, headers: { ...corsHeaders, 'Content-Type': 'application/json' } }
    )
  }
}))
