import { describe, it, expect, beforeAll, afterAll } from "bun:test"

// Importar apenas as funcoes testavel (nao o mock do tls)
// O teste de envio real so roda quando SMTP_INTEGRATION_TEST=true

describe("extractEnvelopeAddress", () => {
  // Testar a funcao de extracao de endereco sem precisar de mock
  const extractEnvelopeAddress = (from: string): string => {
    // Prefer address inside angle brackets
    const angle = from.match(/<\s*([^>\s]+)\s*>/)
    if (angle?.[1]) return angle[1]
    // Fallback: address inside parentheses
    const paren = from.match(/\(([^)\s]+@[^)\s]+)\)/)
    if (paren?.[1]) return paren[1]
    // Fallback: first email-like substring
    const email = from.match(/[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Za-z]{2,}/)
    if (email?.[0]) return email[0]
    // Last resort: use whole string
    return from
  }

  it("extrai endereco de colchetes angulares", () => {
    expect(extractEnvelopeAddress("Nome <email@example.com>")).toBe("email@example.com")
    expect(extractEnvelopeAddress("Sistema <noreply@sistema.com.br>")).toBe("noreply@sistema.com.br")
  })

  it("extrai endereco de parenteses como fallback", () => {
    expect(extractEnvelopeAddress("Chatwoot chat@esdrasrenan.com.br (chat@esdrasrenan.com.br)")).toBe(
      "chat@esdrasrenan.com.br"
    )
  })

  it("extrai endereco direto sem formatacao", () => {
    expect(extractEnvelopeAddress("user@domain.com")).toBe("user@domain.com")
  })

  it("extrai primeiro email de string mista", () => {
    expect(extractEnvelopeAddress("Contato via email test@test.org para suporte")).toBe("test@test.org")
  })

  it("retorna string original se nenhum email encontrado", () => {
    expect(extractEnvelopeAddress("nome-sem-email")).toBe("nome-sem-email")
  })
})

describe("sendSmtpMail - integracao", () => {
  const shouldRunIntegration = process.env.SMTP_INTEGRATION_TEST === "true"

  it.skipIf(!shouldRunIntegration)("envia email via SMTP real", async () => {
    // Este teste so roda quando SMTP_INTEGRATION_TEST=true
    // Para rodar: SMTP_INTEGRATION_TEST=true bun test tests/email-smtp.test.ts
    const { sendSmtpMail } = await import("@/server/email-smtp")

    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 ?? "Sistema de Chamados"

    if (!host || !port || !username || !password || !fromEmail) {
      throw new Error(
        "Variáveis SMTP ausentes. Defina SMTP_HOST, SMTP_PORT, SMTP_USER, SMTP_PASS, SMTP_FROM_EMAIL (e opcionalmente SMTP_FROM_NAME, SMTP_SECURE, SMTP_TEST_TO)."
      )
    }

    const config = {
      host,
      port: Number(port),
      username,
      password,
      from: `"${fromName}" <${fromEmail}>`,
      tls: (process.env.SMTP_SECURE ?? "false").toLowerCase() === "true",
      starttls: (process.env.SMTP_SECURE ?? "false").toLowerCase() !== "true",
      timeoutMs: 30000,
    }

    const to = process.env.SMTP_TEST_TO ?? fromEmail

    await expect(
      sendSmtpMail(config, to, "Teste automático do sistema", "<p>Este é um teste automático.</p>")
    ).resolves.toBeUndefined()
  }, { timeout: 60000 })
})
