import { serve } from "https://deno.land/std@0.190.0/http/server.ts"; import { createClient } from "https://esm.sh/@supabase/supabase-js@2"; const corsHeaders = { "Access-Control-Allow-Origin": "*", "Access-Control-Allow-Headers": "authorization, x-client-info, apikey, content-type", }; interface SendOTPRequest { user_id: string; email: string; } serve(async (req: Request) => { if (req.method === "OPTIONS") { return new Response(null, { headers: corsHeaders }); } try { const { user_id, email }: SendOTPRequest = await req.json(); // Validate required fields if (!user_id || !email) { return new Response( JSON.stringify({ success: false, message: "Missing required fields: user_id, email" }), { status: 400, headers: { ...corsHeaders, "Content-Type": "application/json" } } ); } // Initialize Supabase client with service role const supabaseUrl = Deno.env.get('SUPABASE_URL')!; const supabaseServiceKey = Deno.env.get('SUPABASE_SERVICE_ROLE_KEY')!; const supabase = createClient(supabaseUrl, supabaseServiceKey); // Fetch platform settings for brand name and URL const { data: platformSettings } = await supabase .from('platform_settings') .select('brand_name, platform_url') .single(); const platformName = platformSettings?.brand_name || 'ACCESS HUB'; const platformUrl = platformSettings?.platform_url || 'https://access-hub.com'; console.log(`Generating OTP for user ${user_id}`); // Generate 6-digit OTP code const otpCode = Math.floor(100000 + Math.random() * 900000).toString(); // Calculate expiration time (15 minutes from now) const expiresAt = new Date(Date.now() + 15 * 60 * 1000).toISOString(); // Store OTP in database const { error: insertError } = await supabase .from('auth_otps') .insert({ user_id: user_id, email: email, otp_code: otpCode, expires_at: expiresAt, }); if (insertError) { console.error('Error storing OTP:', insertError); throw new Error(`Failed to store OTP: ${insertError.message}`); } console.log(`OTP generated and stored: ${otpCode}, expires at: ${expiresAt}`); // Send OTP email using send-notification const notificationUrl = `${supabaseUrl}/functions/v1/send-notification`; const notificationResponse = await fetch(notificationUrl, { method: 'POST', headers: { 'Authorization': `Bearer ${supabaseServiceKey}`, 'Content-Type': 'application/json', }, body: JSON.stringify({ template_key: 'auth_email_verification', recipient_email: email, recipient_name: email.split('@')[0], variables: { nama: email.split('@')[0], otp_code: otpCode, email: email, user_id: user_id, expiry_minutes: '15', platform_name: platformName, platform_url: platformUrl } }), }); if (!notificationResponse.ok) { const errorText = await notificationResponse.text(); console.error('Error sending notification email:', notificationResponse.status, errorText); throw new Error(`Failed to send OTP email: ${notificationResponse.status} ${errorText}`); } const notificationResult = await notificationResponse.json(); console.log('Notification sent successfully:', notificationResult); return new Response( JSON.stringify({ success: true, message: "OTP sent successfully" }), { status: 200, headers: { ...corsHeaders, "Content-Type": "application/json" } } ); } catch (error: any) { console.error("Error sending OTP:", error); return new Response( JSON.stringify({ success: false, message: error.message || "Failed to send OTP" }), { status: 500, headers: { ...corsHeaders, "Content-Type": "application/json" } } ); } });