import { describe, expect, it } from 'vitest'
import { UnsupportedOperation, type MarketingAdapter } from './index.js'
import { createAutomation } from './automation.js'
import { makeSelfManagedAdapter } from './self-managed.js'
import { createMemoryComplianceStore } from './compliance.js'

function fakeAdapter(supports: MarketingAdapter['supports']): MarketingAdapter {
  return {
    name: 'fake',
    supports,
    async upsertContact() {},
    async removeContact() {},
    async tagContact() {},
    async createList() {
      return { id: '1', name: 'L' }
    },
    async lists() {
      return []
    },
    async createCampaign(input) {
      return { ...input, id: 'c1' }
    },
    async sendCampaign() {
      return { sent: [], refused: [] }
    },
    async campaignStats() {
      return { opens: 0, clicks: 0, bounces: 0, unsubs: 0 }
    },
    async syncSuppression() {
      return []
    },
    async createAutomation(def) {
      return { id: 'auto-1', name: def.name }
    },
  } as MarketingAdapter & {
    createAutomation: (def: { name: string; listId: string }) => Promise<{ id: string; name: string }>
  }
}

describe('automation capability', () => {
  it('succeeds on a supporting adapter', async () => {
    const adapter = fakeAdapter({ segments: true, scheduling: true, automation: true })
    const automation = await createAutomation(adapter, { name: 'Welcome', listId: '1' })
    expect(automation).toEqual({ id: 'auto-1', name: 'Welcome' })
  })

  it('throws UnsupportedOperation on self-managed (automation unsupported)', async () => {
    const adapter = makeSelfManagedAdapter({
      from: 'news@example.com',
      mail: { send: async () => ({ id: '1', provider: 'fake' }) },
      store: {
        async upsertContact() {},
        async removeContact() {},
        async tagContact() {},
        async createList(name) {
          return { id: 'l1', name }
        },
        async lists() {
          return []
        },
        async saveCampaign() {},
        async getCampaign() {
          return null
        },
        async getListRecipients() {
          return []
        },
        async recordOpen() {},
        async recordClick() {},
        async getStats() {
          return { opens: 0, clicks: 0, bounces: 0, unsubs: 0 }
        },
        async createSegment(def) {
          return { id: 's1', ...def }
        },
        async listSegments() {
          return []
        },
        async scheduleCampaign() {},
      },
      complianceStore: createMemoryComplianceStore(),
    })

    expect(adapter.supports.automation).toBe(false)
    await expect(
      createAutomation(adapter, { name: 'Welcome', listId: '1' }),
    ).rejects.toBeInstanceOf(UnsupportedOperation)
  })
})
