import type { DrizzleClient } from '../client';
import { setSystemConfig } from '../queries/system-config';
import { getVatSchedule, type VatScheduleEntry } from '../queries/vat';

const VAT_SCHEDULE_KEY = 'il.vat_schedule' as const;

/**
 * Fixed timestamp for system-seeded entries so re-runs are deterministic
 * (matches the existing system-seeded 2025 entry's addedAt).
 */
const SEED_ADDED_AT = '2026-05-30T00:00:00.000Z';

/**
 * Authoritative baseline of Israeli VAT rates covering multideal's operational
 * lifetime. multideal post-dates 2015, so the two integer-valued rates below
 * resolve every transaction date the platform can produce:
 *   - 17% effective 2015-10-01 (until 2024-12-31)
 *   - 18% effective 2025-01-01 (current legal rate)
 *
 * Pre-2015 IL rates include fractional values (16.5%, 15.5%) that (a) predate
 * multideal and (b) cannot be represented by the integer `ratePercent` shape;
 * they are intentionally omitted. Any date before 2015-10-01 is unreachable in
 * normal operation and correctly fails loud (NoVatRateError) — there is no
 * fallback rate.
 */
const BASELINE: ReadonlyArray<Omit<VatScheduleEntry, 'addedAt'>> = [
  { effectiveDateIl: '2015-10-01', ratePercent: 17, addedBy: 'system' },
  { effectiveDateIl: '2025-01-01', ratePercent: 18, addedBy: 'system' },
];

/**
 * Idempotent: ensures each baseline rate exists without clobbering admin-added
 * entries (e.g. a future rate change). Re-running is a no-op once all baseline
 * dates are present.
 */
export async function seedVatSchedule(db: DrizzleClient): Promise<void> {
  const existing = await getVatSchedule(db);
  const byDate = new Map(existing.map((e) => [e.effectiveDateIl, e]));

  let changed = false;
  for (const base of BASELINE) {
    if (!byDate.has(base.effectiveDateIl)) {
      byDate.set(base.effectiveDateIl, { ...base, addedAt: SEED_ADDED_AT });
      changed = true;
    }
  }
  if (!changed) return;

  const merged = [...byDate.values()].sort((a, b) =>
    a.effectiveDateIl.localeCompare(b.effectiveDateIl),
  );
  await setSystemConfig(db, VAT_SCHEDULE_KEY, JSON.stringify(merged));
}
