// Edge Function: AI Search ile yer arama
import { createClient } from 'https://esm.sh/@supabase/supabase-js@2.39.3';
import { requireAuth, checkRateLimit } from '../_shared/auth.ts';

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

interface SearchRequest {
  query: string;
}

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

  try {
    // Auth check
    const auth = await requireAuth(req);
    if (auth.error) return auth.error;

    // Rate limit check (20 AI suggestions per hour)
    const supabaseService = createClient(
      Deno.env.get('SUPABASE_URL')!,
      Deno.env.get('SUPABASE_SERVICE_ROLE_KEY')!
    );
    const rateLimitResponse = await checkRateLimit(auth.userId, 'ai_suggest', supabaseService);
    if (rateLimitResponse) return rateLimitResponse;

    const { query }: SearchRequest = await req.json();

    if (!query) {
      return new Response(
        JSON.stringify({ error: 'Arama sorgusu gerekli' }),
        { 
          status: 400, 
          headers: { ...corsHeaders, 'Content-Type': 'application/json' } 
        }
      );
    }

    // AI Search API'ye istek gönder
    const apiKey = Deno.env.get('INTEGRATIONS_API_KEY');
    if (!apiKey) {
      throw new Error('INTEGRATIONS_API_KEY bulunamadı');
    }

    const aiSearchUrl = 'https://app-9w9pd00g5j41-api-zYm4ze3j7XvL.gateway.appmedo.com/v1beta/models/gemini-2.5-flash:streamGenerateContent?alt=sse';
    
    const aiResponse = await fetch(aiSearchUrl, {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json',
        'X-Gateway-Authorization': `Bearer ${apiKey}`,
      },
      body: JSON.stringify({
        contents: [
          {
            role: 'user',
            parts: [
              {
                text: query,
              },
            ],
          },
        ],
      }),
    });

    if (!aiResponse.ok) {
      throw new Error(`AI Search API hatası: ${aiResponse.status}`);
    }

    // Stream yanıtını oku
    const reader = aiResponse.body?.getReader();
    const decoder = new TextDecoder();
    let fullText = '';

    if (reader) {
      while (true) {
        const { done, value } = await reader.read();
        if (done) break;
        
        const chunk = decoder.decode(value);
        const lines = chunk.split('\n');
        
        for (const line of lines) {
          if (line.startsWith('data: ')) {
            try {
              const jsonData = JSON.parse(line.slice(6));
              if (jsonData.candidates?.[0]?.content?.parts?.[0]?.text) {
                fullText += jsonData.candidates[0].content.parts[0].text;
              }
            } catch (e) {
              // JSON parse hatası, devam et
            }
          }
        }
      }
    }

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

  } catch (error) {
    console.error('Edge Function hatası:', error);
    return new Response(
      JSON.stringify({ 
        error: error.message || 'Bilinmeyen hata',
        success: false,
      }),
      { 
        status: 500, 
        headers: { ...corsHeaders, 'Content-Type': 'application/json' } 
      }
    );
  }
});
