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

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

  try {
    const { address, type, width, height } = await req.json();

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

    const apiKey = Deno.env.get('GOOGLE_MAPS_API_KEY');
    if (!apiKey) {
      return new Response(
        JSON.stringify({ success: false, error: 'Google Maps API key not configured' }),
        { status: 500, headers: { ...corsHeaders, 'Content-Type': 'application/json' } }
      );
    }

    const w = width || 320;
    const h = height || 240;
    const encodedAddress = encodeURIComponent(address);

    if (type === 'satellite') {
      // Return a static satellite map URL
      const url = `https://maps.googleapis.com/maps/api/staticmap?center=${encodedAddress}&zoom=18&size=${w}x${h}&maptype=satellite&key=${apiKey}`;
      const response = await fetch(url);
      
      if (!response.ok) {
        return new Response(
          JSON.stringify({ success: false, error: `Static map request failed: ${response.status}` }),
          { status: response.status, headers: { ...corsHeaders, 'Content-Type': 'application/json' } }
        );
      }

      const imageBuffer = await response.arrayBuffer();
      return new Response(imageBuffer, {
        headers: { ...corsHeaders, 'Content-Type': 'image/png', 'Cache-Control': 'public, max-age=86400' },
      });
    }

    // Default: Street View
    // First check if Street View is available via metadata
    const metaUrl = `https://maps.googleapis.com/maps/api/streetview/metadata?location=${encodedAddress}&key=${apiKey}`;
    const metaRes = await fetch(metaUrl);
    const metaData = await metaRes.json();

    if (metaData.status !== 'OK') {
      return new Response(
        JSON.stringify({ success: false, available: false, error: 'Street View not available' }),
        { status: 200, headers: { ...corsHeaders, 'Content-Type': 'application/json' } }
      );
    }

    // Street View is available, fetch the image
    const svUrl = `https://maps.googleapis.com/maps/api/streetview?size=${w}x${h}&location=${encodedAddress}&fov=90&heading=0&pitch=5&key=${apiKey}`;
    const svRes = await fetch(svUrl);

    if (!svRes.ok) {
      return new Response(
        JSON.stringify({ success: false, error: `Street View request failed: ${svRes.status}` }),
        { status: svRes.status, headers: { ...corsHeaders, 'Content-Type': 'application/json' } }
      );
    }

    const svBuffer = await svRes.arrayBuffer();
    return new Response(svBuffer, {
      headers: { ...corsHeaders, 'Content-Type': 'image/jpeg', 'Cache-Control': 'public, max-age=86400' },
    });
  } catch (error) {
    console.error('Google Maps proxy error:', error);
    return new Response(
      JSON.stringify({ success: false, error: error instanceof Error ? error.message : 'Unknown error' }),
      { status: 500, headers: { ...corsHeaders, 'Content-Type': 'application/json' } }
    );
  }
});
