import type { EntityManager } from 'typeorm';
import { allocateInvoiceNumber } from './receipt-sequence.helper';

describe('allocateInvoiceNumber', () => {
  const managerReturning = (n: number) =>
    ({ query: jest.fn().mockResolvedValue([{ last_number: n }]) }) as unknown as EntityManager & {
      query: jest.Mock;
    };

  it('keeps the original INV-YYYY-NNNN format by default (yearly)', async () => {
    const m = managerReturning(7);
    const r = await allocateInvoiceNumber(m, 't1', 2026, {
      prefix: 'INV',
      padding: 4,
      reset: 'yearly',
      start: 1,
    });
    expect(r).toEqual({ invoice_no: 'INV-2026-0007', invoice_year: 2026 });
    expect(m.query.mock.calls[0][1]).toEqual(['t1', 2026, 1]);
  });

  it('never-reset uses one running counter (year 0) and no year in the number', async () => {
    const m = managerReturning(60);
    const r = await allocateInvoiceNumber(m, 't1', 2026, {
      prefix: 'INV',
      padding: 6,
      reset: 'never',
      start: 60,
    });
    expect(r.invoice_no).toBe('INV-000060');
    // Sequence key year 0; start passed for GREATEST(…, start).
    expect(m.query.mock.calls[0][1]).toEqual(['t1', 0, 60]);
    expect(m.query.mock.calls[0][0]).toContain('GREATEST');
  });

  it('is tenant-scoped — the tenant id is always the first query parameter', async () => {
    const m = managerReturning(1);
    await allocateInvoiceNumber(m, 'tenant-b', 2026, {
      prefix: 'GT',
      padding: 4,
      reset: 'yearly',
      start: 1,
    });
    expect(m.query.mock.calls[0][1][0]).toBe('tenant-b');
  });

  it('crashes rather than issue a blank number', async () => {
    const m = { query: jest.fn().mockResolvedValue([]) } as unknown as EntityManager;
    await expect(
      allocateInvoiceNumber(m, 't1', 2026, {
        prefix: 'INV',
        padding: 4,
        reset: 'yearly',
        start: 1,
      }),
    ).rejects.toThrow();
  });
});
