import { describe, expect, it } from 'vitest'
import {
  extractInvoiceBusinessIdentity,
  normalizeInvoiceSettings,
} from '../../src/queries/settings-invoices'

describe('extractInvoiceBusinessIdentity', () => {
  it('reads invoice business identity from tenant settings keys', () => {
    expect(
      extractInvoiceBusinessIdentity(
        {
          business_type: 'osek_morshe',
          tax_id: '514000000',
          vat_number: 'IL514000000',
          logo_url: 'https://cdn.example/logo.png',
        },
        null,
      ),
    ).toEqual({
      business_type: 'osek_morshe',
      business_tax_id: '514000000',
      vat_registration_number: 'IL514000000',
      logo_url: 'https://cdn.example/logo.png',
    })
  })

  it('prefers the typed tenant logo url when present', () => {
    expect(
      extractInvoiceBusinessIdentity(
        { logo_url: 'https://cdn.example/old.png' },
        'https://cdn.example/current.png',
    ).logo_url,
    ).toBe('https://cdn.example/current.png')
  })

  it('normalizes automation settings from tenant settings json', () => {
    expect(
      normalizeInvoiceSettings({
        settings: {
          auto_send_retainer_invoice: true,
          task_status_trigger: {
            enabled: true,
            status_id: 'done',
            invoice_type: 'sent',
          },
        },
        logoUrl: null,
        defaultCurrency: 'ILS',
        defaultPaymentTermsDays: 30,
        defaultTaxRate: '0.18',
        invoiceNumberPrefix: 'INV-',
        issueTaxInvoices: true,
        proformaNumberPrefix: 'PROFORMA-',
        lateFeeType: 'none',
        lateFeeAmount: null,
        lateFeeThresholdDays: 30,
        invoiceFooterText: null,
        invoiceShowPaymentLink: true,
      }),
    ).toEqual(
      expect.objectContaining({
        auto_send_retainer_invoice: true,
        task_status_trigger: {
          enabled: true,
          status_id: 'done',
          invoice_type: 'sent',
        },
      }),
    )
  })

  it('drops invalid task status trigger payloads instead of surfacing partial data', () => {
    expect(
      normalizeInvoiceSettings({
        settings: {
          task_status_trigger: {
            enabled: true,
            status_id: '',
            invoice_type: 'queued',
          },
        },
        logoUrl: null,
        defaultCurrency: 'ILS',
        defaultPaymentTermsDays: 30,
        defaultTaxRate: '0.18',
        invoiceNumberPrefix: 'INV-',
        issueTaxInvoices: true,
        proformaNumberPrefix: 'PROFORMA-',
        lateFeeType: 'none',
        lateFeeAmount: null,
        lateFeeThresholdDays: 30,
        invoiceFooterText: null,
        invoiceShowPaymentLink: true,
      }).task_status_trigger,
    ).toBeNull()
  })
})
