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'

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

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

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

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

    // Get environment variables
    const shoprenterClientId = Deno.env.get('SHOPRENTER_APP_CLIENT_ID')
    const frontendUrl = Deno.env.get('FRONTEND_URL') || 'https://shopcall.ai'

    if (!shoprenterClientId) {
      console.error('SHOPRENTER_APP_CLIENT_ID not configured')
      return new Response(
        JSON.stringify({ error: 'ShopRenter integration not configured' }),
        { status: 500, headers: { ...corsHeaders, 'Content-Type': 'application/json' } }
      )
    }

    // Generate state parameter for CSRF protection
    const state = crypto.randomUUID()

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

    // Verify phone number is available
    const { data: phoneNumber, error: phoneError } = await supabase
      .from('phone_numbers')
      .select('id, is_available')
      .eq('id', phoneNumberId)
      .single()

    if (phoneError || !phoneNumber) {
      console.error('[ShopRenter] Phone number not found:', phoneError)
      return new Response(
        JSON.stringify({ error: 'Invalid phone number selected' }),
        { status: 400, headers: { ...corsHeaders, 'Content-Type': 'application/json' } }
      )
    }

    if (!phoneNumber.is_available) {
      console.error('[ShopRenter] Phone number not available:', phoneNumberId)
      return new Response(
        JSON.stringify({ error: 'Selected phone number is no longer available' }),
        { status: 400, headers: { ...corsHeaders, 'Content-Type': 'application/json' } }
      )
    }

    // Store state in database with user_id and phone_number_id for later validation
    const { error: stateError } = await supabase
      .from('oauth_states')
      .insert({
        state,
        user_id: user.id,
        platform: 'shoprenter',
        shopname,
        phone_number_id: phoneNumberId,
        expires_at: new Date(Date.now() + 15 * 60 * 1000).toISOString() // 15 minutes
      })

    if (stateError) {
      console.error('Error storing state:', stateError)
      return new Response(
        JSON.stringify({ error: 'Failed to initiate OAuth flow' }),
        { status: 500, headers: { ...corsHeaders, 'Content-Type': 'application/json' } }
      )
    }

    // In ShopRenter, users must install the app from their admin panel
    // We return the installation URL that the user should visit
    const installUrl = `https://${shopname}.myshoprenter.hu/admin/app/${shoprenterClientId}`

    return new Response(
      JSON.stringify({
        success: true,
        installUrl,
        message: 'Please visit the installation URL to authorize the app'
      }),
      { status: 200, headers: { ...corsHeaders, 'Content-Type': 'application/json' } }
    )
}))
