import { createClient } from 'https://esm.sh/@supabase/supabase-js@2'

const EXPO_PUSH_URL = 'https://exp.host/--/api/v2/push/send';

Deno.serve(async (req) => {
  const supabase = createClient(
    Deno.env.get('SUPABASE_URL') ?? '',
    Deno.env.get('SUPABASE_SERVICE_ROLE_KEY') ?? ''
  )

  try {
    const payload = await req.json();
    // Payload do Webhook do Supabase: { record: { user_id, message, ... } }
    const { record } = payload;

    if (!record || !record.user_id) {
       return new Response("No record found", { status: 400 });
    }

    // 1. Obter o token do utilizador
    const { data: profile, error } = await supabase
      .from('profiles')
      .select('fcm_token')
      .eq('id', record.user_id)
      .single();

    if (error || !profile?.fcm_token) {
      console.log(`No token found for user ${record.user_id}`);
      return new Response("No token found", { status: 200 });
    }

    const expoToken = profile.fcm_token;
    if (!expoToken.startsWith('ExponentPushToken')) {
      console.log(`Invalid Expo token for user ${record.user_id}`);
      return new Response("Invalid token", { status: 200 });
    }

    // 2. Enviar para o Expo
    const notification = {
      to: expoToken,
      sound: 'default',
      title: 'Smart Agenda',
      body: record.message,
      data: { notificationId: record.id },
    };

    const response = await fetch(EXPO_PUSH_URL, {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json',
        'Accept': 'application/json',
      },
      body: JSON.stringify(notification),
    });

    const result = await response.json();
    console.log('Expo Result:', result);

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

  } catch (err) {
    console.error('Error sending push notification:', err);
    return new Response(JSON.stringify({ error: err.message }), {
      headers: { "Content-Type": "application/json" },
      status: 500,
    });
  }
})
