import {Resend} from 'resend'

import {env} from '../env'

type MagicLinkEmail = {
  to: string
  url: string
}

export const sendMagicLinkEmail = async ({
  to,
  url,
}: MagicLinkEmail) => {
  if (env.NODE_ENV !== 'production') {
    console.log(`\n[dev] magic link for ${to}\n${url}\n`)
    return
  }
  const resend = new Resend(env.RESEND_API_KEY)
  const {error} = await resend.emails.send({
    from: env.EMAIL_FROM,
    to,
    subject: 'Sign in to crumbs',
    text: `Tap to sign in: ${url}\n\nThis link expires in 10 minutes.`,
    html: `<p>Tap to sign in to crumbs:</p><p><a href="${url}">${url}</a></p><p>This link expires in 10 minutes. If you didn't request it, ignore this email.</p>`,
  })
  if (error) throw new Error(`resend error: ${error.message}`)
}
