/**
 * VAPI Manual Setup
 *
 * Manually triggers VAPI setup for an existing store.
 * Used for testing or re-triggering setup for stores that were created
 * before VAPI integration was added.
 *
 * Usage: POST /functions/v1/vapi-manual-setup
 * Body: { "store_id": "uuid" }
 * Auth: Bearer token (service role or user with store access)
 */

import { serve } from 'https://deno.land/std@0.168.0/http/server.ts'
import { createClient } from 'https://esm.sh/@supabase/supabase-js@2'
import { setupVapiForStore } from '../_shared/vapi-setup.ts'

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

serve(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')!

    // Verify authorization
    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 supabaseAdmin = createClient(supabaseUrl, supabaseServiceKey)

    // Parse request body
    const { store_id } = await req.json()

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

    console.log(`[VAPI Manual Setup] Starting setup for store: ${store_id}`)

    // Get store details
    const { data: store, error: storeError } = await supabaseAdmin
      .from('stores')
      .select('id, store_name, phone_number_id, alt_data')
      .eq('id', store_id)
      .single()

    if (storeError || !store) {
      console.error('[VAPI Manual Setup] Store not found:', storeError)
      return new Response(
        JSON.stringify({ error: 'Store not found' }),
        { status: 404, headers: { ...corsHeaders, 'Content-Type': 'application/json' } }
      )
    }

    // Check if already has VAPI assistant
    if (store.alt_data?.vapi_assistant_id) {
      return new Response(
        JSON.stringify({
          error: 'Store already has a VAPI assistant configured',
          vapi_assistant_id: store.alt_data.vapi_assistant_id,
          vapi_phone_number_id: store.alt_data.vapi_phone_number_id
        }),
        { status: 400, headers: { ...corsHeaders, 'Content-Type': 'application/json' } }
      )
    }

    // Get phone number
    if (!store.phone_number_id) {
      return new Response(
        JSON.stringify({ error: 'Store has no phone number assigned' }),
        { status: 400, headers: { ...corsHeaders, 'Content-Type': 'application/json' } }
      )
    }

    const { data: phoneData, error: phoneError } = await supabaseAdmin
      .from('phone_numbers')
      .select('phone_number')
      .eq('id', store.phone_number_id)
      .single()

    if (phoneError || !phoneData) {
      console.error('[VAPI Manual Setup] Phone number not found:', phoneError)
      return new Response(
        JSON.stringify({ error: 'Phone number not found' }),
        { status: 404, headers: { ...corsHeaders, 'Content-Type': 'application/json' } }
      )
    }

    // Format phone number to E.164 (remove spaces)
    const phoneNumber = phoneData.phone_number.replace(/\s/g, '')

    console.log(`[VAPI Manual Setup] Store: ${store.store_name}, Phone: ${phoneNumber}`)

    // Run VAPI setup
    const result = await setupVapiForStore(
      supabaseAdmin,
      store.id,
      store.store_name,
      phoneNumber
    )

    if (result.success) {
      console.log(`[VAPI Manual Setup] Success! Assistant ID: ${result.vapiAssistantId}`)
      return new Response(
        JSON.stringify({
          success: true,
          message: 'VAPI setup completed successfully',
          vapi_assistant_id: result.vapiAssistantId,
          vapi_phone_number_id: result.vapiPhoneNumberId
        }),
        { status: 200, headers: { ...corsHeaders, 'Content-Type': 'application/json' } }
      )
    } else {
      console.error(`[VAPI Manual Setup] Failed:`, result.error)
      return new Response(
        JSON.stringify({
          success: false,
          error: result.error,
          vapi_phone_number_id: result.vapiPhoneNumberId // May have partial success
        }),
        { status: 500, headers: { ...corsHeaders, 'Content-Type': 'application/json' } }
      )
    }

  } catch (error) {
    console.error('[VAPI Manual Setup] Unexpected error:', error)
    return new Response(
      JSON.stringify({
        error: error instanceof Error ? error.message : 'Unexpected error'
      }),
      { status: 500, headers: { ...corsHeaders, 'Content-Type': 'application/json' } }
    )
  }
})
