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

/**
 * Get pending ShopRenter installation info including shop settings.
 * This endpoint is public (no auth required) since the user may not be logged in yet.
 *
 * Input: { installation_id: string }
 * Output: {
 *   success: boolean,
 *   shopname: string,
 *   shop_email?: string,
 *   shop_owner_name?: string,
 *   email_exists: boolean // true if shop_email is already registered in profiles
 * }
 */
serve(wrapHandler('get-pending-install-info', async (req) => {
  if (req.method === 'OPTIONS') {
    return new Response('ok', { headers: corsHeaders })
  }

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

  try {
    const { installation_id } = await req.json()

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

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

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

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

    // Check if installation has expired
    const expiresAt = new Date(pendingInstall.expires_at)
    if (expiresAt < new Date()) {
      console.log('[get-pending-install-info] Installation expired:', installation_id)
      return new Response(
        JSON.stringify({ success: false, error: 'Installation expired' }),
        { status: 410, headers: { ...corsHeaders, 'Content-Type': 'application/json' } }
      )
    }

    // Check if the shop_email already exists in profiles
    let emailExists = false
    if (pendingInstall.shop_email) {
      const { data: existingProfile, error: profileError } = await supabase
        .from('profiles')
        .select('id')
        .eq('email', pendingInstall.shop_email)
        .maybeSingle()

      if (!profileError && existingProfile) {
        emailExists = true
      }
    }

    console.log(`[get-pending-install-info] Returning info for ${pendingInstall.shopname}, email_exists: ${emailExists}`)

    return new Response(
      JSON.stringify({
        success: true,
        shopname: pendingInstall.shopname,
        shop_email: pendingInstall.shop_email || null,
        shop_owner_name: pendingInstall.shop_owner_name || null,
        email_exists: emailExists
      }),
      { status: 200, headers: { ...corsHeaders, 'Content-Type': 'application/json' } }
    )

  } catch (error) {
    console.error('[get-pending-install-info] Error:', error)
    return new Response(
      JSON.stringify({ success: false, error: 'Internal server error' }),
      { status: 500, headers: { ...corsHeaders, 'Content-Type': 'application/json' } }
    )
  }
}))
