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 UpdateRequest {
  company_name?: string;
  source?: string;
}

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('[tenant-profile-update] No auth header');
      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('[tenant-profile-update] Auth error:', authError?.message);
      return new Response(
        JSON.stringify({ success: true, message: 'Skipped - invalid auth' }),
        { headers: { ...corsHeaders, 'Content-Type': 'application/json' } }
      );
    }

    const { company_name, source } = await req.json() as UpdateRequest;

    console.log('[tenant-profile-update] Received request:', {
      user_id: user.id,
      company_name,
      source,
    });

    // 如果没有提供公司名称，跳过
    if (!company_name || company_name.trim() === '') {
      return new Response(
        JSON.stringify({ success: true, message: 'Skipped - no company name' }),
        { headers: { ...corsHeaders, 'Content-Type': 'application/json' } }
      );
    }

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

    if (existingProfile) {
      // 更新公司名称
      const { error: updateError } = await supabase
        .from('tenant_profiles')
        .update({
          company_name: company_name.trim(),
          metadata: {
            company_name_source: source || 'unknown',
            company_name_updated_at: new Date().toISOString(),
          },
          updated_at: new Date().toISOString(),
        })
        .eq('user_id', user.id);

      if (updateError) {
        console.error('[tenant-profile-update] Update error:', updateError);
      } else {
        console.log('[tenant-profile-update] Updated company name');
      }
    } else {
      // 创建新记录
      const { error: insertError } = await supabase
        .from('tenant_profiles')
        .insert({
          user_id: user.id,
          company_name: company_name.trim(),
          metadata: {
            company_name_source: source || 'unknown',
            created_via: 'profile_update',
          },
        });

      if (insertError) {
        console.error('[tenant-profile-update] Insert error:', insertError);
      } else {
        console.log('[tenant-profile-update] Created profile with company name');
      }
    }

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

  } catch (error) {
    console.error('[tenant-profile-update] 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' } }
    );
  }
});
