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

interface ConfirmRequest {
  raw_input: string;
  inferred_problem: string;
  confidence: number;
  user_confirmed: boolean;
}

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

  try {
    const supabaseUrl = Deno.env.get('SUPABASE_URL')!;
    const supabaseServiceKey = Deno.env.get('SUPABASE_SERVICE_ROLE_KEY')!;
    
    // 获取用户 token
    const authHeader = req.headers.get('Authorization');
    if (!authHeader) {
      console.log('[cold-start-confirm] No auth header, skipping profile creation');
      return new Response(
        JSON.stringify({ success: true, message: 'Skipped - no auth' }),
        { headers: { ...corsHeaders, 'Content-Type': 'application/json' } }
      );
    }

    // 创建客户端
    const supabase = createClient(supabaseUrl, supabaseServiceKey);
    
    // 验证用户
    const token = authHeader.replace('Bearer ', '');
    const { data: { user }, error: authError } = await supabase.auth.getUser(token);
    
    if (authError || !user) {
      console.log('[cold-start-confirm] Auth error:', authError?.message);
      return new Response(
        JSON.stringify({ success: true, message: 'Skipped - invalid auth' }),
        { headers: { ...corsHeaders, 'Content-Type': 'application/json' } }
      );
    }

    const { raw_input, inferred_problem, confidence, user_confirmed } = await req.json() as ConfirmRequest;

    console.log('[cold-start-confirm] Received request:', {
      user_id: user.id,
      inferred_problem,
      confidence,
      user_confirmed,
    });

    // 检查是否已存在 tenant_profile
    const { data: existingProfile } = await supabase
      .from('tenant_profiles')
      .select('id, first_task_completed')
      .eq('user_id', user.id)
      .single();

    if (existingProfile) {
      // 更新现有记录
      const { error: updateError } = await supabase
        .from('tenant_profiles')
        .update({
          first_task_completed: true,
          updated_at: new Date().toISOString(),
        })
        .eq('user_id', user.id);

      if (updateError) {
        console.error('[cold-start-confirm] Update error:', updateError);
      } else {
        console.log('[cold-start-confirm] Updated existing profile');
      }
    } else {
      // 创建新记录
      const { error: insertError } = await supabase
        .from('tenant_profiles')
        .insert({
          user_id: user.id,
          first_natural_input: raw_input,
          inferred_problem_type: inferred_problem,
          first_task_completed: true,
          onboarding_completed_at: new Date().toISOString(),
          metadata: {
            confidence,
            user_confirmed,
            created_via: 'cold_start',
          },
        });

      if (insertError) {
        console.error('[cold-start-confirm] Insert error:', insertError);
      } else {
        console.log('[cold-start-confirm] Created new tenant profile');
      }
    }

    return new Response(
      JSON.stringify({ success: true }),
      { headers: { ...corsHeaders, 'Content-Type': 'application/json' } }
    );

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