import { serve } from "https://deno.land/std@0.168.0/http/server.ts"
import { createClient } from 'jsr:@supabase/supabase-js@2';
import { requireAuth, checkRateLimit } from '../_shared/auth.ts';

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

serve(async (req) => {
  if (req.method === 'OPTIONS') {
    return new Response('ok', { 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 { destination } = await req.json()
    const apiKey = Deno.env.get('INTEGRATIONS_API_KEY')
    
    if (!apiKey) {
      throw new Error('INTEGRATIONS_API_KEY is not set')
    }

    const apiUrl = "https://app-9w9pd00g5j41-api-zYm4ze3j7XvL.gateway.appmedo.com/v1beta/models/gemini-2.5-flash:streamGenerateContent?alt=sse";

    const response = await fetch(apiUrl, {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json',
        'X-Gateway-Authorization': `Bearer ${apiKey}`,
      },
      body: JSON.stringify({
        contents: [
          {
            role: "user",
            parts: [
              {
                text: `${destination} için en iyi seyahat ipuçlarını ve mutlaka görülmesi gereken yerleri kısa maddeler halinde Türkçe olarak açıkla. Kaynak linkleri de ekle.`
              }
            ]
          }
        ]
      })
    })

    if (!response.ok) {
      const errorText = await response.text();
      console.error('API Error:', errorText);
      throw new Error(`API returned ${response.status}: ${errorText}`);
    }

    // Proxy the stream
    return new Response(response.body, {
      headers: { 
        ...corsHeaders, 
        'Content-Type': 'text/event-stream',
        'Cache-Control': 'no-cache',
        'Connection': 'keep-alive'
      },
    })

  } catch (error) {
    console.error('Edge Function Error:', error);
    return new Response(JSON.stringify({ error: error.message }), {
      status: 400,
      headers: { ...corsHeaders, 'Content-Type': 'application/json' },
    })
  }
})
