/**
 * Resend transactional email sender.
 *
 * Mirrors the shape of `src/lib/sms/aliyun.ts` so the auth layer can treat
 * both channels uniformly.
 *
 * Docs: https://resend.com/docs/api-reference/emails/send-email
 */

const apiKey = process.env.RESEND_API_KEY || ''
const fromAddress = process.env.RESEND_FROM || 'Forge <onboarding@resend.dev>'
const appName = process.env.RESEND_APP_NAME || 'Forge'

export interface EmailResult {
  success: boolean
  messageId?: string
  error?: string
}

export type OTPType = 'sign-in' | 'email-verification' | 'forget-password' | 'change-email'

function subjectFor(type: OTPType): string {
  switch (type) {
    case 'sign-in':
      return `Your ${appName} sign-in code`
    case 'email-verification':
      return `Verify your email for ${appName}`
    case 'forget-password':
      return `Reset your ${appName} password`
    case 'change-email':
      return `Confirm your new ${appName} email`
  }
}

function purposeLine(type: OTPType): string {
  switch (type) {
    case 'sign-in':
      return `Use the code below to sign in to ${appName}.`
    case 'email-verification':
      return `Use the code below to verify your email address.`
    case 'forget-password':
      return `Use the code below to reset your password.`
    case 'change-email':
      return `Use the code below to confirm your new email address.`
  }
}

function renderHtml(otp: string, type: OTPType): string {
  return `<!doctype html>
<html><body style="margin:0;padding:0;background:#0b0d12;font-family:-apple-system,BlinkMacSystemFont,'Segoe UI',Roboto,sans-serif;">
  <table role="presentation" width="100%" cellpadding="0" cellspacing="0" style="background:#0b0d12;padding:40px 0;">
    <tr><td align="center">
      <table role="presentation" width="440" cellpadding="0" cellspacing="0" style="background:#14171f;border:1px solid #232733;border-radius:16px;padding:32px;">
        <tr><td>
          <div style="font-size:20px;font-weight:600;color:#f4f5f7;margin-bottom:8px;">${appName}</div>
          <div style="font-size:14px;color:#9aa0aa;margin-bottom:24px;">${purposeLine(type)}</div>
          <div style="font-size:32px;font-weight:700;letter-spacing:8px;color:#f4f5f7;background:#1c2030;border:1px solid #2a2f3e;border-radius:12px;padding:18px;text-align:center;font-family:'SF Mono',Menlo,monospace;">${otp}</div>
          <div style="font-size:12px;color:#6b7280;margin-top:24px;line-height:1.6;">
            This code expires in 5 minutes. If you didn't request it, you can safely ignore this email.
          </div>
        </td></tr>
      </table>
    </td></tr>
  </table>
</body></html>`
}

function renderText(otp: string, type: OTPType): string {
  return `${purposeLine(type)}\n\nCode: ${otp}\n\nThis code expires in 5 minutes. If you didn't request it, you can safely ignore this email.`
}

/**
 * Send a one-time password to the given email via Resend.
 */
export async function sendResendOTP(
  email: string,
  otp: string,
  type: OTPType,
): Promise<EmailResult> {
  if (!apiKey) {
    return { success: false, error: 'Resend 未配置：请设置 RESEND_API_KEY' }
  }

  try {
    const response = await fetch('https://api.resend.com/emails', {
      method: 'POST',
      headers: {
        Authorization: `Bearer ${apiKey}`,
        'Content-Type': 'application/json',
      },
      body: JSON.stringify({
        from: fromAddress,
        to: [email],
        subject: subjectFor(type),
        html: renderHtml(otp, type),
        text: renderText(otp, type),
      }),
    })

    const data = (await response.json().catch(() => null)) as { id?: string; message?: string; name?: string } | null

    if (!response.ok) {
      const message = data?.message || data?.name || `Resend HTTP ${response.status}`
      console.error('Resend 邮件发送失败:', data)
      return { success: false, error: message }
    }

    return { success: true, messageId: data?.id }
  } catch (error) {
    console.error('发送 Resend 邮件失败:', error)
    return {
      success: false,
      error: error instanceof Error ? error.message : '未知错误',
    }
  }
}
