import nodemailer from 'nodemailer'

const transporter = nodemailer.createTransport({
  host: process.env.SMTP_HOST,
  port: Number(process.env.SMTP_PORT ?? 587),
  secure: Number(process.env.SMTP_PORT ?? 587) === 465,
  auth: {
    user: process.env.SMTP_USER,
    pass: process.env.SMTP_PASS,
  },
})

interface MfaResetEmailOptions {
  to: string
  userName: string
  resetByName: string
  setupUrl: string
  expiresInHours?: number
}

export async function sendMfaResetEmail(opts: MfaResetEmailOptions) {
  const { to, userName, resetByName, setupUrl, expiresInHours = 24 } = opts
  const from = process.env.SMTP_FROM ?? `"ConsultarTI" <noreply@consultarti.com.br>`

  const html = `
<!DOCTYPE html>
<html lang="pt-BR">
<head>
  <meta charset="UTF-8" />
  <meta name="viewport" content="width=device-width, initial-scale=1.0" />
  <title>Autenticação em dois fatores removida</title>
</head>
<body style="margin:0;padding:0;background:#f4f4f5;font-family:'Segoe UI',Arial,sans-serif;">
  <table role="presentation" width="100%" cellpadding="0" cellspacing="0" style="background:#f4f4f5;padding:40px 16px;">
    <tr>
      <td align="center">
        <table role="presentation" width="100%" style="max-width:560px;background:#ffffff;border-radius:12px;overflow:hidden;box-shadow:0 1px 3px rgba(0,0,0,0.08);">

          <!-- Header -->
          <tr>
            <td style="background:#0f172a;padding:28px 36px;">
              <table role="presentation" width="100%" cellpadding="0" cellspacing="0">
                <tr>
                  <td>
                    <div style="display:inline-flex;align-items:center;gap:10px;">
                      <div style="width:36px;height:36px;background:#3b82f6;border-radius:8px;display:inline-flex;align-items:center;justify-content:center;">
                        <span style="color:#fff;font-weight:700;font-size:16px;">C</span>
                      </div>
                      <span style="color:#ffffff;font-size:18px;font-weight:700;vertical-align:middle;margin-left:10px;">ConsultarTI</span>
                    </div>
                  </td>
                </tr>
              </table>
            </td>
          </tr>

          <!-- Alerta de segurança -->
          <tr>
            <td style="background:#fef3c7;padding:14px 36px;border-bottom:1px solid #fde68a;">
              <p style="margin:0;font-size:13px;color:#92400e;font-weight:600;">
                &#9888;&#65039; Aviso de segurança — ação realizada em sua conta
              </p>
            </td>
          </tr>

          <!-- Corpo -->
          <tr>
            <td style="padding:36px 36px 24px;">
              <h1 style="margin:0 0 8px;font-size:20px;font-weight:700;color:#0f172a;">
                Autenticação em dois fatores removida
              </h1>
              <p style="margin:0 0 24px;font-size:14px;color:#64748b;line-height:1.6;">
                Olá, <strong style="color:#0f172a;">${userName}</strong>.
              </p>
              <p style="margin:0 0 24px;font-size:14px;color:#475569;line-height:1.6;">
                O administrador <strong style="color:#0f172a;">${resetByName}</strong> removeu o seu autenticador MFA (Google Authenticator ou similar) do Portal de Serviços ConsultarTI.
              </p>

              <!-- Caixa de destaque -->
              <table role="presentation" width="100%" cellpadding="0" cellspacing="0" style="margin-bottom:28px;">
                <tr>
                  <td style="background:#f1f5f9;border-left:4px solid #3b82f6;border-radius:0 8px 8px 0;padding:16px 20px;">
                    <p style="margin:0;font-size:13px;color:#334155;line-height:1.6;">
                      Se <strong>você solicitou</strong> essa ação ou estava ciente, clique no botão abaixo para cadastrar um novo autenticador e manter sua conta protegida.
                    </p>
                    <p style="margin:10px 0 0;font-size:13px;color:#ef4444;font-weight:600;">
                      Se <strong>você não solicitou</strong> essa ação, entre em contato imediatamente com o suporte da ConsultarTI.
                    </p>
                  </td>
                </tr>
              </table>

              <!-- Botão CTA -->
              <table role="presentation" cellpadding="0" cellspacing="0" style="margin:0 auto 28px;">
                <tr>
                  <td style="border-radius:8px;background:#3b82f6;">
                    <a href="${setupUrl}" style="display:inline-block;padding:14px 32px;font-size:14px;font-weight:600;color:#ffffff;text-decoration:none;border-radius:8px;">
                      Cadastrar novo MFA
                    </a>
                  </td>
                </tr>
              </table>

              <p style="margin:0 0 4px;font-size:12px;color:#94a3b8;line-height:1.6;">
                Este link é pessoal, intransferível e expira em <strong>${expiresInHours} horas</strong>.
              </p>
              <p style="margin:0;font-size:12px;color:#94a3b8;line-height:1.6;">
                Caso o botão não funcione, copie e cole o endereço abaixo no seu navegador:
              </p>
              <p style="margin:6px 0 0;font-size:11px;color:#3b82f6;word-break:break-all;">${setupUrl}</p>
            </td>
          </tr>

          <!-- Rodapé -->
          <tr>
            <td style="background:#f8fafc;border-top:1px solid #e2e8f0;padding:20px 36px;">
              <p style="margin:0;font-size:11px;color:#94a3b8;line-height:1.6;">
                Este e-mail foi gerado automaticamente pelo Portal de Serviços ConsultarTI.
                Por favor, não responda a esta mensagem.
              </p>
              <p style="margin:8px 0 0;font-size:11px;color:#cbd5e1;">
                &copy; ${new Date().getFullYear()} ConsultarTI. Todos os direitos reservados.
              </p>
            </td>
          </tr>

        </table>
      </td>
    </tr>
  </table>
</body>
</html>
`

  await transporter.sendMail({
    from,
    to,
    subject: '[ConsultarTI] Autenticação em dois fatores removida da sua conta',
    html,
    text: `Olá ${userName},\n\nO administrador ${resetByName} removeu o seu autenticador MFA.\n\nCadastre um novo em: ${setupUrl}\n\nEste link expira em ${expiresInHours} horas.\n\nSe você não solicitou essa ação, contate o suporte imediatamente.\n\nConsultarTI`,
  })
}
