/**
 * Israel country adapter — system-i18n.
 *
 * `createIsraelAdapter(db)` preloads the full IL VAT history from the DB once,
 * so the synchronous `CountryAdapter.getVatRate(date)` can do an in-memory
 * find over the preloaded rates — honouring the spec's sync interface while
 * remaining DB-driven for the historical rates.
 *
 * VAT history is ordered DESC so Array.prototype.find() returns the most
 * recent rate on or before `date` in O(n) with a small, bounded history.
 */
import { desc, eq } from 'drizzle-orm'
import type { CountryAdapter } from '@zync/types'
import type { Db } from '../client'
import { vatRates } from '../schema/vat-rates'

export async function createIsraelAdapter(db: Db): Promise<CountryAdapter> {
  // Preload the IL VAT history once; sync getVatRate does an in-memory find.
  const rates = await db
    .select({ effectiveFrom: vatRates.effectiveFrom, rate: vatRates.rate })
    .from(vatRates)
    .where(eq(vatRates.countryCode, 'IL'))
    .orderBy(desc(vatRates.effectiveFrom))

  return {
    code: 'IL',
    name: 'Israel',
    defaultCurrency: 'ILS',
    defaultTimezone: 'Asia/Jerusalem',
    getVatRate: (date: Date): number => {
      const hit = rates.find((r) => new Date(r.effectiveFrom) <= date)
      return hit ? Number(hit.rate) : 0
    },
    vatLabel: 'מע"מ',
    invoiceRequirements: {
      requiresTaxId: true,
      taxIdLabel: 'ע.מ / ח.פ',
      requiresSequentialNumbering: true,
      allowsVatExemptZeroRate: true,
      retentionYears: 7,
    },
  }
}
