import { beforeEach, describe, expect, it, vi } from 'vitest'
import { sendViaResend } from '../../../../../../packages/notifications/src/email/resend'
import { buildMailMessage } from '../../../../../../packages/notifications/src/email/send-email'

const resendSendMock = vi.fn()

vi.mock('resend', () => ({
  Resend: vi.fn().mockImplementation(() => ({
    emails: { send: resendSendMock },
  })),
}))

describe('mail platform parity', () => {
  beforeEach(() => {
    vi.clearAllMocks()
    vi.resetModules()
  })

  it('matches the legacy Resend request payload for rendered host email', async () => {
    const fetchMock = vi.fn().mockResolvedValue(
      new Response(JSON.stringify({ id: 'legacy-mail-id' }), {
        status: 200,
        headers: { 'content-type': 'application/json' },
      }),
    )
    const originalFetch = globalThis.fetch
    globalThis.fetch = fetchMock as typeof globalThis.fetch

    try {
      const [{ sendMail }] = await Promise.all([import('../mail')])

      const options = {
        to: 'owner@example.com',
        templateKey: 'invoice-sent',
        vars: {
          subject: 'Invoice INV-42 ready',
          customer_name: 'Acme Ltd',
          invoice_number: 'INV-42',
          invoice_link: 'https://app.zync.is/invoices/INV-42',
          tenantLocale: 'en-US',
        },
        locale: 'en-US',
        tags: {
          invoice_id: 'invoice-42',
          tenant_id: 'tenant-7',
        },
      } as const
      const env = { RESEND_API_KEY: 'resend-key' }

      const message = buildMailMessage(options)

      const legacyTags = message.tags
        ? Object.entries(message.tags).map(([name, value]) => ({ name, value }))
        : undefined

      await sendViaResend(
        {
          from: message.from,
          to: message.to,
          subject: message.subject,
          html: message.html ?? '',
          text: message.text,
          reply_to: message.replyTo,
          tags: legacyTags,
        },
        env.RESEND_API_KEY,
      )

      await sendMail(env, message)

      const legacyPayload = JSON.parse(fetchMock.mock.calls[0]?.[1]?.body as string)
      const platformPayload = resendSendMock.mock.calls[0]?.[0]

      expect(platformPayload).toEqual(legacyPayload)
      expect(resendSendMock.mock.calls[0]?.[1]).toBeUndefined()
    } finally {
      globalThis.fetch = originalFetch
    }
  })
})
