import { beforeEach, describe, expect, it, vi } from 'vitest'

const mockGetInvoiceForAdapterPush = vi.fn()

vi.mock('@zync/db/queries', async () => {
  const actual = await vi.importActual<Record<string, unknown>>('@zync/db/queries')
  return {
    ...actual,
    getInvoiceForAdapterPush: (...args: unknown[]) => mockGetInvoiceForAdapterPush(...args),
  }
})

import { createMorningAdapter } from '../src/integrations/invoice-adapters'

describe('invoice adapters query layer routing', () => {
  beforeEach(() => {
    vi.clearAllMocks()
    vi.stubGlobal(
      'fetch',
      vi.fn().mockResolvedValue({
        ok: true,
        json: async () => ({ id: 'ext-1' }),
      }),
    )
    mockGetInvoiceForAdapterPush.mockResolvedValue({
      invoiceNumber: 'INV-1',
      proformaNumber: null,
      customerId: 'customer-1',
      total: '100.00',
      currency: 'ILS',
      taxIssueDate: '2026-07-03',
      issueDate: '2026-07-03',
      status: 'TAX_ISSUED',
      customerName: 'Acme',
      customerEmail: 'billing@example.com',
    })
  })

  it('loads invoice payloads through the query layer instead of db.execute', async () => {
    const adapter = createMorningAdapter({
      provider: 'morning',
      apiKey: 'key',
      metadata: {},
    })
    const db = {
      execute: vi.fn(),
    }

    await expect(adapter.pushInvoice('invoice-1', 'tenant-1', db as never)).resolves.toBe('ext-1')

    expect(mockGetInvoiceForAdapterPush).toHaveBeenCalledWith(db, 'tenant-1', 'invoice-1')
    expect(db.execute).not.toHaveBeenCalled()
  })
})
