import { serve } from "https://deno.land/std@0.168.0/http/server.ts" import { createClient } from 'https://esm.sh/@supabase/supabase-js@2.7.1' const corsHeaders = { 'Access-Control-Allow-Origin': '*', 'Access-Control-Allow-Headers': 'authorization, x-client-info, apikey, content-type', } serve(async (req) => { // 1. GESTIONE CORS if (req.method === 'OPTIONS') { return new Response('ok', { headers: corsHeaders }) } try { // 2. ESTRAZIONE EMAIL const { email } = await req.json() if (!email) { throw new Error("Devi fornire un indirizzo email.") } // 3. INIZIALIZZAZIONE CLIENT ADMIN const supabaseAdmin = createClient( Deno.env.get('SUPABASE_URL') ?? '', Deno.env.get('SUPABASE_SERVICE_ROLE_KEY') ?? '' ) // 4. RECUPERO NOME UTENTE (Opzionale, ma fa molto pro per l'email) const { data: staffData } = await supabaseAdmin .from('staff_members') .select('name') .eq('email', email) .single() const userName = staffData?.name || "Socio" // 5. GENERAZIONE DEL LINK DI RECOVERY // Usiamo lo stesso identico URL di redirect che abbiamo blindato prima! const { data: linkData, error: linkError } = await supabaseAdmin.auth.admin.generateLink({ type: 'recovery', email: email, options: { redirectTo: 'https://flux.catelli.it/set-password' } }) if (linkError) { // Se l'utente non esiste su Auth, Supabase lancia un errore. // Per sicurezza (evitare l'enumerazione delle email), restituiamo comunque un 200 finto // oppure intercettiamo l'errore per il debug. console.error("Errore generazione link Supabase:", linkError) throw new Error("Se l'email è registrata, riceverai a breve le istruzioni.") } const secureLink = linkData.properties.action_link // 6. IL POSTINO RESEND const RESEND_API_KEY = Deno.env.get('RESEND_API_KEY') if (!RESEND_API_KEY) throw new Error("Chiave API di Resend non configurata.") const emailHtml = `
Ciao ${userName},
Abbiamo ricevuto una richiesta per reimpostare la password del tuo account su FLUX. Clicca sul pulsante qui sotto per sceglierne una nuova.
Se non hai richiesto tu il ripristino, puoi ignorare tranquillamente questa email. Il link è strettamente personale e valido per un solo utilizzo.
${secureLink}