import * as React from "react"
import dotenv from "dotenv"
import { render } from "@react-email/render"

import { sendSmtpMail } from "@/server/email-smtp"
import AutomationEmail, { type AutomationEmailProps } from "../emails/automation-email"

dotenv.config({ path: ".env.local" })
dotenv.config({ path: ".env" })

type CliArgs = {
  to: string
  subject: string
}

function parseArgs(argv: string[]): CliArgs {
  const args = argv.slice(2)
  const get = (key: string) => {
    const idx = args.findIndex((a) => a === key)
    if (idx === -1) return null
    return args[idx + 1] ?? null
  }

  return {
    to: get("--to") || process.env.TEST_EMAIL_TO || "monkeyesdras@gmail.com",
    subject: get("--subject") || "Teste de e-mail — React Email (Raven)",
  }
}

function getSmtpConfig() {
  const host = process.env.SMTP_HOST
  const port = process.env.SMTP_PORT
  const username = process.env.SMTP_USER
  const password = process.env.SMTP_PASS
  const fromEmail = process.env.SMTP_FROM_EMAIL
  const fromName = process.env.SMTP_FROM_NAME ?? "Raven"

  if (!host || !port || !username || !password || !fromEmail) return null

  return {
    host,
    port: Number(port),
    username,
    password,
    from: `"${fromName}" <${fromEmail}>`,
    tls: process.env.SMTP_SECURE === "true",
    rejectUnauthorized: false,
    timeoutMs: 15000,
  }
}

function buildTestEmailProps(subject: string): AutomationEmailProps {
  const baseUrl = process.env.NEXT_PUBLIC_APP_URL || process.env.APP_BASE_URL || "http://localhost:3000"

  return {
    title: subject,
    message:
      "Olá!\n\nEste é um e-mail de teste gerado pelo React Email, usando o design do Raven.\n\nSe você recebeu esta mensagem, o SMTP está funcionando corretamente.",
    ticket: {
      reference: 99999,
      subject: "Teste de automação (envio de e-mail)",
      companyName: "Cliente de Teste",
      status: "PENDING",
      priority: "MEDIUM",
      requesterName: "Solicitante",
      assigneeName: "Administrador",
    },
    ctaLabel: "Abrir Raven",
    ctaUrl: `${baseUrl}/login`,
    preview: "Teste de e-mail do Raven",
  }
}

async function main() {
  const { to, subject } = parseArgs(process.argv)

  const smtp = getSmtpConfig()
  if (!smtp) {
    console.error(
      "SMTP não configurado. Defina SMTP_HOST, SMTP_PORT, SMTP_USER, SMTP_PASS, SMTP_FROM_EMAIL (e opcionalmente SMTP_FROM_NAME/SMTP_SECURE)."
    )
    process.exit(1)
  }

  const props = buildTestEmailProps(subject)
  const html = await render(<AutomationEmail {...props} />, { pretty: true })

  await sendSmtpMail(smtp, to, subject, html)

  console.log(`OK: e-mail enviado para ${to}`)
}

main().catch((error) => {
  console.error("Falha ao enviar e-mail de teste:", error)
  process.exit(1)
})
