import { serve } from 'https://deno.land/std@0.168.0/http/server.ts'; import { createClient } from 'https://esm.sh/@supabase/supabase-js@2'; import { corsHeaders } from '../_shared/cors.ts'; import { edgeLogger, startRequest, endRequest } from '../_shared/logger.ts'; interface EmailRequest { email: string; displayName?: string; username?: string; } serve(async (req) => { const tracking = startRequest(); if (req.method === 'OPTIONS') { return new Response(null, { headers: { ...corsHeaders, 'X-Request-ID': tracking.requestId } }); } try { const supabaseClient = createClient( Deno.env.get('SUPABASE_URL') ?? '', Deno.env.get('SUPABASE_ANON_KEY') ?? '', { global: { headers: { Authorization: req.headers.get('Authorization')! }, }, } ); const { data: { user }, error: userError } = await supabaseClient.auth.getUser(); if (userError || !user) { const duration = endRequest(tracking); edgeLogger.error('Authentication failed', { action: 'send_password_email', requestId: tracking.requestId, duration }); throw new Error('Unauthorized'); } const { email, displayName, username }: EmailRequest = await req.json(); if (!email) { throw new Error('Email is required'); } edgeLogger.info('Sending password added email', { action: 'send_password_email', requestId: tracking.requestId, userId: user.id, email }); const recipientName = displayName || username || 'there'; const siteUrl = Deno.env.get('SITE_URL') || 'https://thrillwiki.com'; const emailHTML = `

Password Successfully Added

Hi ${recipientName},

Great news! A password has been successfully added to your ThrillWiki account (${email}).

✅ What This Means

You now have an additional way to access your account. You can sign in using:

🔐 Complete Your Setup

Important: To complete your password setup, you need to confirm your email address.

  1. Check your inbox for a confirmation email from ThrillWiki
  2. Click the confirmation link in that email
  3. Return to the sign-in page and log in with your email and password
Go to Sign In Page

Note: You must confirm your email before you can sign in with your password.

⚠️ Security Notice
If you didn't add a password to your account, please contact our support team immediately at support@thrillwiki.com

Thanks for being part of the ThrillWiki community!

Best regards,
The ThrillWiki Team

`; const forwardEmailKey = Deno.env.get('FORWARDEMAIL_API_KEY'); const fromEmail = Deno.env.get('FROM_EMAIL_ADDRESS') || 'noreply@thrillwiki.com'; if (!forwardEmailKey) { edgeLogger.error('FORWARDEMAIL_API_KEY not configured', { requestId: tracking.requestId }); throw new Error('Email service not configured'); } const emailResponse = await fetch('https://api.forwardemail.net/v1/emails', { method: 'POST', headers: { 'Content-Type': 'application/json', 'Authorization': `Basic ${btoa(forwardEmailKey + ':')}`, }, body: JSON.stringify({ from: fromEmail, to: email, subject: 'Password Added to Your ThrillWiki Account', html: emailHTML, }), }); if (!emailResponse.ok) { const errorText = await emailResponse.text(); edgeLogger.error('ForwardEmail API error', { requestId: tracking.requestId, status: emailResponse.status, errorText }); throw new Error(`Failed to send email: ${emailResponse.statusText}`); } const duration = endRequest(tracking); edgeLogger.info('Password addition email sent successfully', { action: 'send_password_email', requestId: tracking.requestId, userId: user.id, email, duration }); return new Response( JSON.stringify({ success: true, message: 'Password addition email sent successfully', requestId: tracking.requestId, }), { status: 200, headers: { ...corsHeaders, 'Content-Type': 'application/json', 'X-Request-ID': tracking.requestId }, } ); } catch (error) { const duration = endRequest(tracking); edgeLogger.error('Error in send-password-added-email function', { action: 'send_password_email', requestId: tracking.requestId, duration, error: error instanceof Error ? error.message : 'Unknown error' }); return new Response( JSON.stringify({ success: false, error: error instanceof Error ? error.message : 'Unknown error', requestId: tracking.requestId, }), { status: 500, headers: { ...corsHeaders, 'Content-Type': 'application/json', 'X-Request-ID': tracking.requestId }, } ); } });