/**
 * Get AI Context Edge Function
 *
 * Example implementation showing how to retrieve AI context data
 * that respects store_data_exclusions. Only enabled items are included.
 *
 * Related to issue #46: Integrate exclusions with AI context
 *
 * Usage:
 * GET /get-ai-context?store_id=<uuid>&format=json|prompt
 *
 * Query parameters:
 * - store_id (required): UUID of the store
 * - format (optional): 'json' (default) or 'prompt' (formatted text)
 * - data_types (optional): Comma-separated list of types (product,order,customer)
 * - limit (optional): Limit items per data type
 */

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, logError } from '../_shared/error-handler.ts'
import { getAIContext, formatAIContextAsPrompt } from '../_shared/ai-context-builder.ts'

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

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

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

    // Parse query parameters
    const url = new URL(req.url)
    const storeId = url.searchParams.get('store_id')
    const format = url.searchParams.get('format') || 'json'
    const dataTypesParam = url.searchParams.get('data_types')
    const limitParam = url.searchParams.get('limit')

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

    // Verify store belongs to user
    const { data: store, error: storeError } = await supabase
      .from('stores')
      .select('id')
      .eq('id', storeId)
      .eq('user_id', user.id)
      .single()

    if (storeError || !store) {
      return new Response(
        JSON.stringify({ error: 'Store not found or access denied' }),
        { status: 404, headers: { ...corsHeaders, 'Content-Type': 'application/json' } }
      )
    }

    // Parse data types
    let dataTypes: ('product' | 'order' | 'customer')[] = ['product', 'order', 'customer']
    if (dataTypesParam) {
      const types = dataTypesParam.split(',').map(t => t.trim()) as ('product' | 'order' | 'customer')[]
      const validTypes = types.filter(t => ['product', 'order', 'customer'].includes(t))
      if (validTypes.length > 0) {
        dataTypes = validTypes
      }
    }

    // Parse limit
    const limit = limitParam ? parseInt(limitParam) : undefined

    // Use service role key for full database access (respecting RLS via store ownership check above)
    const supabaseServiceKey = Deno.env.get('SUPABASE_SERVICE_ROLE_KEY')!
    const supabaseAdmin = createClient(supabaseUrl, supabaseServiceKey)

    // Get AI context using the helper function
    console.log(`[AI Context] Fetching context for store ${storeId}, types: ${dataTypes.join(', ')}`)
    const startTime = Date.now()

    const context = await getAIContext(supabaseAdmin, {
      storeId,
      dataTypes,
      limit,
      includeDisabled: false  // Only include enabled items
    })

    const duration = Date.now() - startTime
    console.log(`[AI Context] Context built in ${duration}ms: ${context.metadata.total_items} items`)

    // Return in requested format
    if (format === 'prompt') {
      // Return as formatted text prompt for LLM
      const promptText = formatAIContextAsPrompt(context)
      return new Response(
        promptText,
        { status: 200, headers: { ...corsHeaders, 'Content-Type': 'text/plain' } }
      )
    } else {
      // Return as structured JSON
      return new Response(
        JSON.stringify({
          success: true,
          context,
          performance: {
            duration_ms: duration
          }
        }),
        { status: 200, headers: { ...corsHeaders, 'Content-Type': 'application/json' } }
      )
    }

}))
