import { serve } from "https://deno.land/std@0.168.0/http/server.ts";
import { createClient } from "https://esm.sh/@supabase/supabase-js@2";

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

serve(async (req) => {
  // Handle CORS preflight requests
  if (req.method === 'OPTIONS') {
    return new Response(null, { headers: corsHeaders });
  }

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

    // Get auth header for user identification
    const authHeader = req.headers.get('Authorization');
    if (!authHeader) {
      return new Response(
        JSON.stringify({ error: 'Missing authorization header' }),
        { status: 401, headers: { ...corsHeaders, 'Content-Type': 'application/json' } }
      );
    }

    // Verify 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 token' }),
        { status: 401, headers: { ...corsHeaders, 'Content-Type': 'application/json' } }
      );
    }

    const { session_id, create_if_not_exists = true } = await req.json();

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

    console.log(`[context-read] Reading context for session: ${session_id}, user: ${user.id}`);

    // Try to fetch existing context
    let { data: context, error: fetchError } = await supabase
      .from('agent_context')
      .select('*')
      .eq('session_id', session_id)
      .eq('user_id', user.id)
      .maybeSingle();

    if (fetchError) {
      console.error('[context-read] Fetch error:', fetchError);
      return new Response(
        JSON.stringify({ error: 'Failed to fetch context', details: fetchError.message }),
        { status: 500, headers: { ...corsHeaders, 'Content-Type': 'application/json' } }
      );
    }

    // Create new context if not exists and requested
    if (!context && create_if_not_exists) {
      console.log(`[context-read] Creating new context for session: ${session_id}`);
      
      const { data: newContext, error: createError } = await supabase
        .from('agent_context')
        .insert({
          session_id,
          user_id: user.id,
          conversation_context: {
            current_agent: null,
            intent: null,
            turn_count: 0,
            last_message: null
          },
          domain_context: {
            store_manager: {},
            product_manager: {},
            marketing_manager: {},
            service_manager: {},
            finance_manager: {}
          },
          selected_items: {
            products: [],
            orders: [],
            coupons: [],
            campaigns: [],
            users: []
          },
          version: 1
        })
        .select()
        .single();

      if (createError) {
        // Handle race condition - another request might have created it
        if (createError.code === '23505') {
          const { data: existingContext } = await supabase
            .from('agent_context')
            .select('*')
            .eq('session_id', session_id)
            .eq('user_id', user.id)
            .single();
          context = existingContext;
        } else {
          console.error('[context-read] Create error:', createError);
          return new Response(
            JSON.stringify({ error: 'Failed to create context', details: createError.message }),
            { status: 500, headers: { ...corsHeaders, 'Content-Type': 'application/json' } }
          );
        }
      } else {
        context = newContext;
      }
    }

    if (!context) {
      return new Response(
        JSON.stringify({ error: 'Context not found', session_id }),
        { status: 404, headers: { ...corsHeaders, 'Content-Type': 'application/json' } }
      );
    }

    console.log(`[context-read] Successfully read context, version: ${context.version}`);

    return new Response(
      JSON.stringify({
        success: true,
        context: {
          id: context.id,
          session_id: context.session_id,
          conversation_context: context.conversation_context,
          domain_context: context.domain_context,
          selected_items: context.selected_items,
          version: context.version,
          updated_at: context.updated_at
        }
      }),
      { headers: { ...corsHeaders, 'Content-Type': 'application/json' } }
    );

  } catch (error) {
    console.error('[context-read] Unexpected error:', error);
    return new Response(
      JSON.stringify({ error: 'Internal server error', details: ((error instanceof Error ? error.message : String(error))) }),
      { status: 500, headers: { ...corsHeaders, 'Content-Type': 'application/json' } }
    );
  }
});
