import { BadRequestException, NotFoundException, ValidationPipe } from '@nestjs/common';
import { Test } from '@nestjs/testing';
import { plainToInstance } from 'class-transformer';
import { validate } from 'class-validator';
import { BulkGenerateInvoiceDto, BULK_INVOICE_MAX } from './dto/bulk-generate-invoice.dto';
import { getRepositoryToken } from '@nestjs/typeorm';
import { ClsService } from 'nestjs-cls';
import { AccountingController } from './accounting.controller';
import { AccountingService } from './accounting.service';
import { GenerateInvoiceDto } from './dto/generate-invoice.dto';
import { CustomerInvoiceRepository } from './repositories/customer-invoice.repository';
import { BookingService } from '../booking/booking.service';
import { BankAccountService } from '../bank-account/bank-account.service';
import { BookingHotelItemEntity } from '../../entities/booking-hotel-item.entity';
import { BookingTransportItemEntity } from '../../entities/booking-transport-item.entity';
import { BookingActivityItemEntity } from '../../entities/booking-activity-item.entity';
import { BookingSpecialItemEntity } from '../../entities/booking-special-item.entity';
import { TenantSettingsEntity } from '../../entities/tenant-settings.entity';
import { AccessLevel, ModuleName } from '../../entities/role-permission.entity';
import { PERMISSION_KEY } from '../../auth/decorators/permissions.decorator';
import { CLS_TENANT_ID } from '../../common/cls/cls.constants';

/**
 * Tax invoice totals, tax, currency, numbering and failure cases.
 * Line layout and Bill To are covered in accounting.service.spec.ts.
 */
describe('Customer tax invoice', () => {
  let service: AccountingService;
  const managerQuery = jest.fn();
  const managerFindOne = jest.fn();
  const invoices = {
    save: jest.fn((x) => Promise.resolve({ id: 'inv-1', ...x })),
    findById: jest.fn(),
    findForBooking: jest.fn(),
    findLatestForBooking: jest.fn(),
    update: jest.fn(),
    manager: { query: managerQuery, findOne: managerFindOne },
  };
  const settingsRepo = { findOne: jest.fn() };
  const bankAccounts = { findInvoiceDefault: jest.fn() };
  const bookingService = { findById: jest.fn() };
  const cls = { get: jest.fn((k: string) => (k === CLS_TENANT_ID ? 't1' : null)) };

  beforeEach(async () => {
    const module = await Test.createTestingModule({
      providers: [
        AccountingService,
        { provide: ClsService, useValue: cls },
        { provide: getRepositoryToken(BookingHotelItemEntity), useValue: {} },
        { provide: getRepositoryToken(BookingTransportItemEntity), useValue: {} },
        { provide: getRepositoryToken(BookingActivityItemEntity), useValue: {} },
        { provide: getRepositoryToken(BookingSpecialItemEntity), useValue: {} },
        { provide: getRepositoryToken(TenantSettingsEntity), useValue: settingsRepo },
        { provide: CustomerInvoiceRepository, useValue: invoices },
        { provide: BankAccountService, useValue: bankAccounts },
        { provide: BookingService, useValue: bookingService },
      ],
    }).compile();
    service = module.get(AccountingService);
    settingsRepo.findOne.mockResolvedValue(null);
    managerQuery.mockResolvedValue([{ last_number: 7 }]);
    managerFindOne.mockResolvedValue(null);
  });

  afterEach(() => jest.resetAllMocks());
  beforeEach(() => {
    invoices.save.mockImplementation((x) => Promise.resolve({ id: 'inv-1', ...x }));
    cls.get.mockImplementation((k: string) => (k === CLS_TENANT_ID ? 't1' : null));
  });

  const base = {
    id: 'bk-1',
    currency_id: 'aed',
    selling_currency_id: 'aed',
    exchange_rate: 1,
    selling_total: 0,
    markup_tax_amount: 0,
    grand_total: 1000,
    guest_name: 'Mr. Karan',
    guest_mobile: '9999',
    guest_email: 'k@example.com',
    destination: { name: 'Dubai' },
    start_date: '2026-07-20',
    end_date: '2026-07-25',
    adults: 2,
    children_ages: [6],
    infants: 1,
    hotel_items: [],
    transport_items: [],
    activity_items: [],
    special_items: [],
    flight_details: [],
  };
  const generate = async (over: Record<string, unknown> = {}) => {
    bookingService.findById.mockResolvedValue({ ...base, ...over });
    return service.generateCustomerInvoice({ booking_id: 'bk-1' });
  };
  const special = (total: number, tax = 0, snap: unknown = null, date = '2026-07-21') => ({
    service_name: 'Guide',
    total_price: total,
    tax_amount: tax,
    tax_snapshot: snap,
    date,
  });

  describe('totals', () => {
    it('without a selling total, bills the cost total and adds no service line', async () => {
      const inv = await generate({ special_items: [special(1000)] });
      expect(inv.grand_total).toBe(1000);
      expect(inv.subtotal).toBe(1000);
      expect(inv.tax_total).toBe(0);
      expect(inv.line_items!.map((l) => l.kind)).toEqual(['SPECIAL']);
    });

    it('adds the markup as a Service charge so the total equals the selling total', async () => {
      const inv = await generate({ selling_total: 1150, special_items: [special(1000)] });
      const svc = inv.line_items!.find((l) => l.kind === 'SERVICE')!;
      expect(svc.description).toBe('Service charge');
      expect(svc.line_total).toBe(150);
      expect(inv.grand_total).toBe(1150);
    });

    it('shows a selling total below cost as a Discount', async () => {
      const inv = await generate({ selling_total: 900, special_items: [special(1000)] });
      const svc = inv.line_items!.find((l) => l.kind === 'SERVICE')!;
      expect(svc.description).toBe('Discount');
      expect(svc.line_total).toBe(-100);
      expect(inv.grand_total).toBe(900);
    });

    it('ignores a rounding-only gap (no 0.00 service line)', async () => {
      const inv = await generate({ selling_total: 1000.004, special_items: [special(1000)] });
      expect(inv.line_items!.some((l) => l.kind === 'SERVICE')).toBe(false);
    });

    it('always keeps subtotal + tax = total', async () => {
      const snap = { slab_id: 's', total_rate: 5, components: [{ name: 'VAT', rate: 5 }] };
      const inv = await generate({
        selling_total: 1234.56,
        markup_tax_amount: 11.11,
        special_items: [special(1000, 47.62, snap)],
      });
      expect(+(Number(inv.subtotal) + Number(inv.tax_total)).toFixed(2)).toBe(inv.grand_total);
      expect(inv.grand_total).toBe(1234.56);
    });

    it('never stores a negative subtotal', async () => {
      const snap = { slab_id: 's', total_rate: 5, components: [{ name: 'VAT', rate: 5 }] };
      const inv = await generate({ grand_total: 10, special_items: [special(10, 50, snap)] });
      expect(inv.subtotal).toBe(0);
    });
  });

  describe('selling currency', () => {
    it('stores destination-currency totals and freezes the rate', async () => {
      const inv = await generate({
        selling_currency_id: 'usd',
        exchange_rate: 0.27,
        selling_total: 297,
        grand_total: 1000,
      });
      expect(inv.currency_id).toBe('aed');
      expect(inv.selling_currency_id).toBe('usd');
      expect(inv.exchange_rate).toBe(0.27);
      expect(inv.grand_total).toBe(1100);
    });

    it.each([0.27, 0.2723, 1])(
      'prints back exactly what the customer was billed at rate %s',
      async (rate) => {
        for (const selling of [1, 99.99, 135, 1585, 2934, 7043, 87272.55]) {
          const inv = await generate({
            exchange_rate: rate,
            selling_total: selling,
            grand_total: selling / rate - 3,
          });
          expect(+(inv.grand_total * rate).toFixed(2)).toBe(selling);
        }
      },
    );

    it('treats a missing or zero rate as 1', async () => {
      const inv = await generate({ exchange_rate: 0, selling_total: 1100 });
      expect(inv.exchange_rate).toBe(1);
      expect(inv.grand_total).toBe(1100);
    });

    it('converts the tax on the markup back to the stored currency', async () => {
      const inv = await generate({
        exchange_rate: 0.5,
        selling_total: 600,
        markup_tax_amount: 10,
        grand_total: 1000,
      });
      expect(inv.tax_bifurcation![0].amount).toBe(20);
      expect(inv.grand_total).toBe(1200);
    });
  });

  describe('tax breakdown', () => {
    it('splits a line tax across its components by rate', async () => {
      const snap = {
        slab_id: 's',
        total_rate: 18,
        components: [
          { name: 'CGST', rate: 9 },
          { name: 'SGST', rate: 9 },
        ],
      };
      const inv = await generate({ special_items: [special(1000, 180, snap)] });
      expect(inv.tax_bifurcation!.map((t) => [t.tax_type_name, t.rate, t.amount])).toEqual([
        ['CGST', 9, 90],
        ['SGST', 9, 90],
      ]);
      expect(inv.tax_total).toBe(180);
      expect(inv.subtotal).toBe(820);
    });

    it('adds up the same component across hotel, transfer, activity and special', async () => {
      const snap = { slab_id: 's', total_rate: 5, components: [{ name: 'VAT', rate: 5 }] };
      const inv = await generate({
        hotel_items: [{ subtotal: 400, tax_amount: 10, tax_snapshot: snap, periods: [] }],
        transport_items: [{ id: 't', subtotal: 200, tax_amount: 20, tax_snapshot: snap }],
        activity_items: [
          { activity_id: 'a', quantity: 1, subtotal: 100, tax_amount: 30, tax_snapshot: snap },
          { activity_id: 'a', quantity: 1, subtotal: 100, tax_amount: 5, tax_snapshot: snap },
        ],
        special_items: [special(200, 40, snap)],
      });
      expect(inv.tax_bifurcation).toHaveLength(1);
      expect(inv.tax_bifurcation![0].amount).toBe(105);
      expect(inv.tax_total).toBe(105);
    });

    it('keeps two slabs with the same tax name apart', async () => {
      const a = { slab_id: 'a', total_rate: 5, components: [{ name: 'VAT', rate: 5 }] };
      const b = { slab_id: 'b', total_rate: 10, components: [{ name: 'VAT', rate: 10 }] };
      const inv = await generate({ special_items: [special(500, 25, a), special(500, 50, b)] });
      expect(inv.tax_bifurcation!.map((t) => [t.rate, t.amount])).toEqual([
        [5, 25],
        [10, 50],
      ]);
    });

    it('still lists a flat slab that has no components', async () => {
      const snap = { slab_id: 's', slab_name: 'Tourism Fee', total_rate: 7 };
      const inv = await generate({ special_items: [special(1000, 70, snap)] });
      expect(inv.tax_bifurcation![0]).toMatchObject({
        tax_type_name: 'Tourism Fee',
        rate: 7,
        amount: 70,
      });
    });

    describe('lines with no stored tax (real bookings)', () => {
      const vat = {
        slab_id: 's',
        slab_name: 'VAT',
        total_rate: 5,
        components: [{ name: 'VAT', rate: 5 }],
      };

      it('works VAT out of the tax-inclusive prices (MT-362571: 23,499 + 1,175)', async () => {
        const inv = await generate({
          grand_total: 24674.12,
          selling_total: 24674,
          rounding: 1,
          transport_items: [{ id: 't', subtotal: 7682, tax_amount: null, tax_snapshot: vat }],
          activity_items: [
            {
              activity_id: 'a',
              quantity: 1,
              subtotal: 16992.12,
              tax_amount: null,
              tax_snapshot: vat,
            },
          ],
        });
        expect(inv.tax_bifurcation!.map((t) => [t.tax_type_name, t.rate, t.amount])).toEqual([
          ['VAT', 5, 1175],
        ]);
        expect(inv.tax_total).toBe(1175);
        expect(inv.subtotal).toBe(23499);
        expect(inv.grand_total).toBe(24674);
      });

      it('uses the booking rounding, whole units by default', async () => {
        const lines = { special_items: [special(1000, 0, vat)] };
        expect((await generate(lines)).tax_total).toBe(48);
        expect((await generate({ ...lines, rounding: 0.01 })).tax_total).toBe(47.62);
      });

      it('rounds on the whole amount, not line by line', async () => {
        const inv = await generate({
          grand_total: 63,
          special_items: [special(21, 0, vat), special(21, 0, vat), special(21, 0, vat)],
        });
        expect(inv.tax_total).toBe(3);
      });

      it('splits two components', async () => {
        const gst = {
          slab_id: 'g',
          total_rate: 18,
          components: [
            { name: 'CGST', rate: 9 },
            { name: 'SGST', rate: 9 },
          ],
        };
        const inv = await generate({ grand_total: 1180, special_items: [special(1180, 0, gst)] });
        expect(inv.tax_bifurcation!.map((t) => [t.tax_type_name, t.amount])).toEqual([
          ['CGST', 90],
          ['SGST', 90],
        ]);
        expect(inv.subtotal).toBe(1000);
      });

      it('keeps two slabs apart', async () => {
        const b = { slab_id: 'b', total_rate: 10, components: [{ name: 'VAT', rate: 10 }] };
        const inv = await generate({
          grand_total: 1000,
          special_items: [special(525, 0, vat), special(475, 0, b)],
        });
        expect(inv.tax_bifurcation!.map((t) => [t.rate, t.amount])).toEqual([
          [5, 25],
          [10, 43],
        ]);
      });

      it('keeps a frozen tax_amount on older lines and works out the rest', async () => {
        const inv = await generate({
          grand_total: 2050,
          special_items: [special(1000, 47.62, vat), special(1050, 0, vat)],
        });
        expect(inv.tax_total).toBe(97.62);
      });

      it('adds the tax on the service charge on top', async () => {
        const inv = await generate({
          grand_total: 1050,
          selling_total: 1160.5,
          markup_tax_amount: 5.5,
          special_items: [special(1050, 0, vat)],
        });
        expect(inv.tax_bifurcation!.map((t) => t.amount)).toEqual([50, 5.5]);
        expect(inv.grand_total).toBe(1160.5);
        expect(inv.subtotal).toBe(1105);
      });

      it('charges nothing for an exempt slab or a line with no snapshot', async () => {
        const exempt = { slab_id: 'x', total_rate: 0, components: [] };
        const inv = await generate({
          special_items: [special(500, 0, exempt), special(500, 0, null)],
        });
        expect(inv.tax_bifurcation).toEqual([]);
        expect(inv.tax_total).toBe(0);
        expect(inv.subtotal).toBe(1000);
      });

      it('still lists a flat slab with no components', async () => {
        const flat = { slab_id: 'f', slab_name: 'Tourism Fee', total_rate: 5, components: [] };
        const inv = await generate({ grand_total: 1050, special_items: [special(1050, 0, flat)] });
        expect(inv.tax_bifurcation![0]).toMatchObject({ tax_type_name: 'Tourism Fee', amount: 50 });
      });
    });

    it('names the service-charge tax after the slab, read for this tenant only', async () => {
      managerFindOne.mockResolvedValue({
        id: 'sl',
        tax_type_id: 'tt',
        total_rate: 5,
        tax_type: { name: 'VAT' },
      });
      const inv = await generate({
        tax_slab_id: 'sl',
        selling_total: 1105,
        markup_tax_amount: 5,
      });
      expect(managerFindOne.mock.calls[0][1].where).toEqual({ id: 'sl', tenant_id: 't1' });
      expect(inv.tax_bifurcation![0]).toMatchObject({
        tax_type_name: 'VAT on service charge',
        rate: 5,
        amount: 5,
      });
    });

    it('falls back to a plain name when the booking has no slab', async () => {
      const inv = await generate({ selling_total: 1105, markup_tax_amount: 5 });
      expect(managerFindOne).not.toHaveBeenCalled();
      expect(inv.tax_bifurcation![0].tax_type_name).toBe('Tax on service charge');
    });

    it('ignores markup tax when there is no selling total', async () => {
      const inv = await generate({ markup_tax_amount: 5 });
      expect(inv.tax_bifurcation).toEqual([]);
      expect(inv.grand_total).toBe(1000);
    });
  });

  describe('lines', () => {
    it('prints a hotel first, with its stay details and rooms', async () => {
      const inv = await generate({
        special_items: [special(100, 0, null, '2026-07-01')],
        hotel_items: [
          {
            subtotal: 900,
            hotel: { name: 'JW Marriott' },
            check_in_date: '2026-07-20',
            check_out_date: '2026-07-23',
            nights: 3,
            periods: [{ room_type: 'Deluxe', meal_plan: 'BB', rooms: 2, num_rooms: 2 }],
          },
        ],
      });
      const hotel = inv.line_items![0];
      expect(hotel.kind).toBe('HOTEL');
      expect(hotel.details).toEqual(
        expect.arrayContaining([
          'Guest Name : Mr. Karan',
          'Hotel : JW Marriott',
          'Check-In : 20/07/2026',
          'Check-Out : 23/07/2026',
          'Night : 03',
          'Pax : 02 Adults + 1 Child + 1 Infant',
        ]),
      );
    });

    it('splits a transfer amount over its quantity', async () => {
      const inv = await generate({
        transport_items: [
          { id: 't', is_shared: true, quantity: 3, subtotal: 100, date: '2026-07-20' },
        ],
      });
      const t = inv.line_items![0];
      expect(t.qty).toBe(3);
      expect(t.unit_price).toBe(33.33);
      expect(t.line_total).toBe(100);
      expect(t.details).toContain('SIC');
    });

    it('prints every activity row as its own line, never merged or summed', async () => {
      const row = {
        activity_id: 'a',
        ticket_id: 'x',
        date: '2026-07-20',
        activity: { name: 'Burj' },
      };
      const inv = await generate({
        activity_items: [
          { ...row, age_group: 'adult', quantity: 2, subtotal: 200 },
          { ...row, age_group: 'senior', quantity: 1, subtotal: 80 },
          { ...row, age_group: 'child', quantity: 1, subtotal: 50 },
          { ...row, date: '2026-07-21', age_group: 'adult', quantity: 1, subtotal: 100 },
          { ...row, ticket_id: 'y', age_group: 'adult', quantity: 1, subtotal: 90 },
        ],
      });
      expect(inv.line_items!.map((l) => [l.description, l.qty, l.line_total])).toEqual([
        ['Burj - Adult', 2, 200],
        ['Burj - Child', 1, 50],
        ['Burj - Senior', 1, 80],
        ['Burj - Adult', 1, 90],
        ['Burj - Adult', 1, 100],
      ]);
    });

    it('adds the ticket name once and labels the slot', async () => {
      const inv = await generate({
        activity_items: [
          {
            activity_id: 'a',
            ticket_id: 'x',
            quantity: 1,
            subtotal: 10,
            slot: '10:00',
            activity: { name: 'Burj' },
            ticket: { name: 'Top' },
          },
          {
            activity_id: 'b',
            ticket_id: 'y',
            quantity: 1,
            subtotal: 10,
            slot: 'Slot A',
            activity: { name: 'Frame Top' },
            ticket: { name: 'Top' },
          },
        ],
      });
      expect(inv.line_items![0].description).toBe('Burj - Top - Adult');
      expect(inv.line_items![0].details).toContain('Slot - 10:00');
      expect(inv.line_items![1].description).toBe('Frame Top - Adult');
      expect(inv.line_items![1].details).toContain('Slot A');
    });

    it('never divides by zero on an empty quantity', async () => {
      const inv = await generate({
        activity_items: [{ activity_id: 'a', quantity: 0, subtotal: 50, activity: { name: 'X' } }],
      });
      expect(inv.line_items![0].qty).toBe(1);
      expect(inv.line_items![0].unit_price).toBe(50);
    });

    it('prints undated services last', async () => {
      const inv = await generate({
        special_items: [
          { service_name: 'No date', total_price: 1 },
          { service_name: 'Dated', total_price: 1, date: '2026-07-20' },
        ],
      });
      expect(inv.line_items!.map((l) => l.description)).toEqual(['Dated', 'No date']);
    });

    it('prints a Travel Package line for a Quick Booking with no items', async () => {
      const inv = await generate({ grand_total: 500 });
      expect(inv.line_items).toEqual([
        {
          kind: 'SPECIAL',
          description: 'Travel Package',
          qty: 1,
          unit_price: 500,
          line_total: 500,
        },
      ]);
    });
  });

  describe('issue again → refresh the same invoice (client 2026-11-06)', () => {
    const existing = {
      id: 'inv-9',
      invoice_no: 'INV-2026-0009',
      invoice_year: 2026,
      invoice_date: '2026-10-01',
      booking_id: 'bk-1',
      grand_total: 500,
    };

    it('first issue allocates a number and saves a new invoice', async () => {
      invoices.findLatestForBooking.mockResolvedValue(null);
      const inv = await generate();
      expect(invoices.save).toHaveBeenCalledTimes(1);
      expect(invoices.update).not.toHaveBeenCalled();
      expect(inv.invoice_no).toMatch(/^INV-/);
    });

    it('later issue updates the current invoice with the latest totals', async () => {
      invoices.findLatestForBooking.mockResolvedValue(existing);
      const inv = await generate({ grand_total: 1200 });
      expect(invoices.save).not.toHaveBeenCalled();
      expect(invoices.update).toHaveBeenCalledWith(
        'inv-9',
        expect.objectContaining({ grand_total: 1200, guest_name_snapshot: 'Mr. Karan' }),
      );
      expect(inv).toMatchObject({ id: 'inv-9', grand_total: 1200 });
    });

    it('keeps the invoice number and date — no new number is used up', async () => {
      invoices.findLatestForBooking.mockResolvedValue(existing);
      const inv = await generate({ grand_total: 1200 });
      const patch = invoices.update.mock.calls[0][1];
      expect(patch).not.toHaveProperty('invoice_no');
      expect(patch).not.toHaveProperty('invoice_date');
      expect(inv).toMatchObject({ invoice_no: 'INV-2026-0009', invoice_date: '2026-10-01' });
      expect(managerQuery).not.toHaveBeenCalledWith(
        expect.stringMatching(/invoice_sequences|last_number/i),
        expect.anything(),
      );
    });

    it('looks up the current invoice for this booking only', async () => {
      invoices.findLatestForBooking.mockResolvedValue(null);
      await generate();
      expect(invoices.findLatestForBooking).toHaveBeenCalledWith('bk-1');
    });

    it('still refuses a cancelled booking before touching the invoice', async () => {
      invoices.findLatestForBooking.mockResolvedValue(existing);
      await expect(generate({ status: 'cancelled' })).rejects.toThrow(/cancelled/);
      expect(invoices.update).not.toHaveBeenCalled();
    });
  });

  describe('bulk issue / refresh (Invoices page)', () => {
    const run = (ids: string[]) => service.generateCustomerInvoicesBulk(ids);

    it('issues new invoices and refreshes existing ones, reporting which', async () => {
      bookingService.findById.mockResolvedValue({ ...base });
      invoices.findLatestForBooking
        .mockResolvedValueOnce(null) // bk-a: before → new
        .mockResolvedValueOnce(null) // bk-a: inside generate
        .mockResolvedValueOnce({ id: 'inv-old', invoice_no: 'INV-2026-0002' }) // bk-b: before
        .mockResolvedValueOnce({ id: 'inv-old', invoice_no: 'INV-2026-0002' }); // bk-b: inside
      const r = await run(['bk-a', 'bk-b']);
      expect(r.skipped).toEqual([]);
      expect(r.issued).toHaveLength(2);
      expect(r.issued[0]).toMatchObject({ booking_id: 'bk-a', refreshed: false });
      expect(r.issued[1]).toMatchObject({
        booking_id: 'bk-b',
        invoice_id: 'inv-old',
        invoice_no: 'INV-2026-0002',
        refreshed: true,
      });
    });

    it('skips bookings that cannot be invoiced, and carries on', async () => {
      bookingService.findById
        .mockResolvedValueOnce({ ...base, status: 'cancelled' })
        .mockRejectedValueOnce(new NotFoundException('Booking not found')) // not visible
        .mockResolvedValueOnce({ ...base });
      invoices.findLatestForBooking.mockResolvedValue(null);
      const r = await run(['bk-c', 'bk-hidden', 'bk-ok']);
      expect(r.issued.map((x) => x.booking_id)).toEqual(['bk-ok']);
      expect(r.skipped).toEqual([
        { booking_id: 'bk-c', reason: expect.stringMatching(/cancelled/) },
        { booking_id: 'bk-hidden', reason: 'Booking not found' },
      ]);
    });

    it('handles each booking once, in the order given', async () => {
      bookingService.findById.mockResolvedValue({ ...base });
      invoices.findLatestForBooking.mockResolvedValue(null);
      await run(['bk-1', 'bk-2', 'bk-1']);
      expect(bookingService.findById.mock.calls.map((c) => c[0])).toEqual(['bk-1', 'bk-2']);
    });

    it('stops on an unexpected error instead of hiding it', async () => {
      bookingService.findById.mockRejectedValue(new Error('db down'));
      invoices.findLatestForBooking.mockResolvedValue(null);
      await expect(run(['bk-1'])).rejects.toThrow('db down');
    });
  });

  describe('bulk request limits', () => {
    const errorsFor = async (booking_ids: unknown) => {
      const dto = plainToInstance(BulkGenerateInvoiceDto, { booking_ids });
      return validate(dto);
    };
    const uuid = (n: number) => `00000000-0000-4000-8000-${String(n).padStart(12, '0')}`;

    it('accepts 1 to 50 booking ids', async () => {
      expect(await errorsFor([uuid(1)])).toHaveLength(0);
      expect(
        await errorsFor(Array.from({ length: BULK_INVOICE_MAX }, (_, i) => uuid(i))),
      ).toHaveLength(0);
    });

    it('refuses none, more than 50, or non-uuid ids', async () => {
      expect((await errorsFor([])).length).toBeGreaterThan(0);
      expect(
        (await errorsFor(Array.from({ length: BULK_INVOICE_MAX + 1 }, (_, i) => uuid(i)))).length,
      ).toBeGreaterThan(0);
      expect((await errorsFor(['not-a-uuid'])).length).toBeGreaterThan(0);
    });
  });

  describe('saved snapshot', () => {
    it('freezes the guest, destination and travel dates', async () => {
      const inv = await generate();
      expect(inv).toMatchObject({
        booking_id: 'bk-1',
        guest_name_snapshot: 'Mr. Karan',
        guest_mobile_snapshot: '9999',
        guest_email_snapshot: 'k@example.com',
        destination_name_snapshot: 'Dubai',
        travel_start_snapshot: '2026-07-20',
        travel_end_snapshot: '2026-07-25',
      });
    });

    it('takes the currency from the destination when the booking has none', async () => {
      const inv = await generate({ currency_id: null, destination: { currency: { id: 'inr' } } });
      expect(inv.currency_id).toBe('inr');
    });
  });

  describe('numbering', () => {
    it('uses INV-YYYY-0001 style when there are no settings, for this tenant', async () => {
      const inv = await generate();
      const year = Number(
        new Date().toLocaleDateString('en-CA', { timeZone: 'Asia/Kolkata' }).slice(0, 4),
      );
      expect(inv.invoice_no).toBe(`INV-${year}-0007`);
      expect(inv.invoice_year).toBe(year);
      expect(managerQuery.mock.calls[0][1][0]).toBe('t1');
      expect(settingsRepo.findOne.mock.calls[0][0].where.tenant_id).toBe('t1');
    });

    it('gives each re-issue its own number', async () => {
      managerQuery.mockResolvedValueOnce([{ last_number: 8 }]);
      managerQuery.mockResolvedValueOnce([{ last_number: 9 }]);
      const a = await generate();
      const b = await generate();
      expect(a.invoice_no).not.toBe(b.invoice_no);
      expect(invoices.save).toHaveBeenCalledTimes(2);
    });

    it('saves nothing if no number can be allocated', async () => {
      managerQuery.mockResolvedValue([]);
      await expect(generate()).rejects.toThrow('no sequence number');
      expect(invoices.save).not.toHaveBeenCalled();
    });
  });

  describe('invoice date', () => {
    const at = async (iso: string) => {
      jest.useFakeTimers({ now: new Date(iso), doNotFake: ['nextTick', 'setImmediate'] });
      try {
        return await generate();
      } finally {
        jest.useRealTimers();
      }
    };

    it('uses the office day in the early morning, not the UTC day', async () => {
      // 01:30 on 3 Nov in India is still 2 Nov in UTC.
      const inv = await at('2026-11-02T20:00:00Z');
      expect(inv.invoice_date).toBe('2026-11-03');
    });

    it('changes day at midnight India time', async () => {
      expect((await at('2026-11-02T18:29:00Z')).invoice_date).toBe('2026-11-02');
      expect((await at('2026-11-02T18:30:00Z')).invoice_date).toBe('2026-11-03');
    });

    it('stays on the same day in the evening', async () => {
      expect((await at('2026-11-02T15:00:00Z')).invoice_date).toBe('2026-11-02');
    });

    it('numbers a new-year invoice in the new year series', async () => {
      const inv = await at('2026-12-31T20:00:00Z');
      expect(inv.invoice_date).toBe('2027-01-01');
      expect(inv.invoice_year).toBe(2027);
      expect(inv.invoice_no).toBe('INV-2027-0007');
    });

    it('is always stored as YYYY-MM-DD', async () => {
      expect((await at('2026-03-05T06:00:00Z')).invoice_date).toBe('2026-03-05');
    });
  });

  describe('refused', () => {
    it('booking not found: no number used, nothing saved', async () => {
      bookingService.findById.mockResolvedValue(null);
      await expect(service.generateCustomerInvoice({ booking_id: 'x' })).rejects.toBeInstanceOf(
        NotFoundException,
      );
      expect(managerQuery).not.toHaveBeenCalled();
      expect(invoices.save).not.toHaveBeenCalled();
    });

    it('booking with no currency: no number used, nothing saved', async () => {
      await expect(generate({ currency_id: null, destination: null })).rejects.toBeInstanceOf(
        BadRequestException,
      );
      expect(managerQuery).not.toHaveBeenCalled();
      expect(invoices.save).not.toHaveBeenCalled();
    });

    it.each([
      ['cancelled', 'is cancelled'],
      ['on_hold', 'is on hold'],
    ])('%s booking: no number used, nothing saved', async (status, message) => {
      await expect(generate({ status })).rejects.toThrow(message);
      expect(managerQuery).not.toHaveBeenCalled();
      expect(invoices.save).not.toHaveBeenCalled();
    });

    it.each(['upcoming', 'ongoing', 'completed'])(
      '%s booking: invoice is issued',
      async (status) => {
        const inv = await generate({ status });
        expect(inv.grand_total).toBe(1000);
        expect(invoices.save).toHaveBeenCalledTimes(1);
      },
    );

    it.each([
      ['zero total', { grand_total: 0 }],
      ['negative total', { grand_total: -5 }],
      ['selling total cancels out', { grand_total: 100, selling_total: 0.001 }],
    ])('nothing to bill (%s): no number used, nothing saved', async (_name, over) => {
      await expect(generate(over)).rejects.toThrow('nothing to bill');
      expect(managerQuery).not.toHaveBeenCalled();
      expect(invoices.save).not.toHaveBeenCalled();
    });

    it('a failed booking read is passed on, nothing saved', async () => {
      bookingService.findById.mockRejectedValue(new NotFoundException('hidden'));
      await expect(service.generateCustomerInvoice({ booking_id: 'x' })).rejects.toThrow('hidden');
      expect(invoices.save).not.toHaveBeenCalled();
    });

    it.each([['not-a-uuid'], [''], [undefined], [123]])('rejects booking_id %s', async (v) => {
      const pipe = new ValidationPipe({ whitelist: true, forbidNonWhitelisted: true });
      await expect(
        pipe.transform({ booking_id: v }, { type: 'body', metatype: GenerateInvoiceDto }),
      ).rejects.toBeInstanceOf(BadRequestException);
    });

    it('rejects extra fields such as a client-supplied total', async () => {
      const pipe = new ValidationPipe({ whitelist: true, forbidNonWhitelisted: true });
      await expect(
        pipe.transform(
          { booking_id: '8f86625f-83d2-4e07-938d-380342ed5580', grand_total: 1 },
          { type: 'body', metatype: GenerateInvoiceDto },
        ),
      ).rejects.toBeInstanceOf(BadRequestException);
    });
  });

  describe('permissions', () => {
    const required = (method: keyof AccountingController) =>
      Reflect.getMetadata(PERMISSION_KEY, AccountingController.prototype[method]);

    // Client 2026-11-06: anyone who can see bookings issues and opens the
    // tax invoice; the service also checks that particular booking.
    it('issuing and reading need Booking View', () => {
      for (const m of [
        'generateInvoice',
        'generateInvoicesBulk',
        'getInvoice',
        'listForBooking',
      ] as const) {
        expect(required(m)).toEqual({
          module: ModuleName.BOOKING,
          accessLevel: AccessLevel.VIEW,
        });
      }
    });

    it('the other accounting reports still need Accounting View', () => {
      expect(required('taxLedger')).toEqual({
        module: ModuleName.ACCOUNTING,
        accessLevel: AccessLevel.VIEW,
      });
    });
  });

  describe('printed invoice', () => {
    const stored = {
      id: 'inv-1',
      booking_id: 'bk-1',
      invoice_date: '2026-01-30',
      guest_name_snapshot: 'Mr. Karan',
      selling_currency_id: 'usd',
      exchange_rate: 0.27,
      currency_id: 'aed',
    };
    const print = async (over = {}, settings: unknown = null, row: unknown = {}, bank = null) => {
      invoices.findById.mockResolvedValue({ ...stored, ...over });
      settingsRepo.findOne.mockResolvedValue(settings);
      bankAccounts.findInvoiceDefault.mockResolvedValue(bank);
      managerQuery.mockResolvedValue(row ? [row] : []);
      return (await service.findInvoiceById('inv-1')).print;
    };

    it('invoice not found', async () => {
      invoices.findById.mockResolvedValue(null);
      await expect(service.findInvoiceById('x')).rejects.toBeInstanceOf(NotFoundException);
    });

    it('checks the user can see the booking before opening its invoice', async () => {
      await print();
      expect(bookingService.findById).toHaveBeenCalledWith('bk-1');
    });

    it('an invoice of a booking the user cannot see is not found', async () => {
      invoices.findById.mockResolvedValue(stored);
      bookingService.findById.mockRejectedValue(new NotFoundException('Booking not found'));
      await expect(service.findInvoiceById('inv-1')).rejects.toBeInstanceOf(NotFoundException);
    });

    it('prints pax from the booking (adults, children, infants)', async () => {
      const p = await print({}, null, { adults: 2, children_ages: [6, 9], infants: 1 });
      expect(p.pax).toEqual({ adults: 2, children: 2, infants: 1 });
    });

    it('prints zero pax when the booking has none recorded', async () => {
      const p = await print({}, null, {});
      expect(p.pax).toEqual({ adults: 0, children: 0, infants: 0 });
    });

    it('prints in the frozen rate and selling code', async () => {
      const p = await print({}, null, { selling_code: 'USD', selling_symbol: '$' });
      expect(p.currency).toEqual({ code: 'USD', symbol: '$', rate: 0.27 });
    });

    it('prints an old invoice with no selling currency at rate 1', async () => {
      const p = await print({ selling_currency_id: null });
      expect(p.currency.rate).toBe(1);
      expect(managerQuery.mock.calls[0][1]).toEqual(['bk-1', 't1', 'aed']);
    });

    it('works out the due date across a month end, from Invoice Settings', async () => {
      expect((await print({}, { invoice_due_days: 5 })).due_date).toBe('2026-02-04');
      expect((await print({}, { invoice_due_days: 0 })).due_date).toBe('2026-01-30');
      expect((await print({}, null)).due_date).toBe('2026-01-30');
    });

    it('prefers invoice settings over company details', async () => {
      const p = await print(
        {},
        {
          company_name: 'Co',
          invoice_company_name: 'Inv Co',
          phone: '1',
          invoice_phone: '2',
          tax_number: 'T1',
          invoice_trn: 'T2',
          invoice_title: 'Tax Invoice',
        },
      );
      expect(p.issuer).toMatchObject({
        name: 'Inv Co',
        phone: '2',
        trn: 'T2',
        title: 'Tax Invoice',
        signatory: 'For, Inv Co',
      });
    });

    it('falls back to company details and the title Invoice', async () => {
      const p = await print({}, { company_name: 'Co', tax_number: 'T1' });
      expect(p.issuer).toMatchObject({
        name: 'Co',
        trn: 'T1',
        title: 'Invoice',
        signatory: 'For, Co',
      });
    });

    it('prints the agent TRN under Bill To only when entered', async () => {
      const withTrn = await print({}, null, { source_type: 'B2B_AGENT', trn_no: ' 100234 ' });
      expect(withTrn.bill_to.trn).toBe('100234');
      const blank = await print({}, null, { source_type: 'B2B_AGENT', trn_no: '' });
      expect(blank.bill_to.trn).toBeNull();
    });

    it('prints the customer name with the invoice details', async () => {
      const p = await print({}, null, { guest_name: 'Vignesh' });
      expect(p.customer_name).toBe('Vignesh');
    });

    it('uses the agency name when it has no billing name', async () => {
      const p = await print({}, null, { source_type: 'B2B_AGENT', source_name: 'Travclan' });
      expect(p.bill_to.name).toBe('Travclan');
    });

    it('bills the agency on a quick (walk-in) booking for a B2B agent', async () => {
      const p = await print({}, null, {
        source_type: 'B2B_AGENT',
        source_name: 'Travclan',
        is_walk_in: true,
      });
      expect(p.bill_to.name).toBe('Travclan');
    });

    it('bills the guest for a direct trip source', async () => {
      const p = await print({}, null, {
        source_type: 'DIRECT',
        source_name: 'Walking',
        is_walk_in: true,
      });
      expect(p.bill_to).toEqual({
        name: 'Mr. Karan',
        address: '',
        state: null,
        country: null,
        trn: null,
      });
    });

    it('still prints when the booking row is gone', async () => {
      const p = await print({}, null, null);
      expect(p.bill_to.name).toBe('Mr. Karan');
      expect(p.reference).toBeNull();
      expect(p.sales_person).toBeNull();
    });

    it('shows the first sales person, read for this tenant only', async () => {
      invoices.findById.mockResolvedValue(stored);
      settingsRepo.findOne.mockResolvedValue(null);
      bankAccounts.findInvoiceDefault.mockResolvedValue(null);
      managerQuery
        .mockResolvedValueOnce([{ sales_team: ['u1', 'u2'] }])
        .mockResolvedValueOnce([{ name: 'Zeel' }]);
      const { print: p } = await service.findInvoiceById('inv-1');
      expect(p.sales_person).toBe('Zeel');
      expect(managerQuery.mock.calls[1][1]).toEqual(['u1', 't1']);
    });

    it('prints bank details only when a default account exists', async () => {
      expect((await print()).bank).toBeNull();
      const bank = {
        account_name: 'Mellow',
        account_number: '123',
        swift_code: 'S',
        iban: 'I',
        branch: 'B',
        bank: { name: 'ENBD' },
      };
      const p = await print({}, null, {}, bank as never);
      expect(p.bank).toEqual({
        account_name: 'Mellow',
        bank_name: 'ENBD',
        account_number: '123',
        swift_code: 'S',
        iban: 'I',
        branch: 'B',
      });
    });

    it('lists invoices for a booking through the tenant repository', async () => {
      invoices.findForBooking.mockResolvedValue([{ id: 'a' }]);
      await expect(service.findInvoicesForBooking('bk-1')).resolves.toEqual([{ id: 'a' }]);
      expect(invoices.findForBooking).toHaveBeenCalledWith('bk-1');
      expect(bookingService.findById).toHaveBeenCalledWith('bk-1');
    });

    it('does not list invoices of a booking the user cannot see', async () => {
      bookingService.findById.mockRejectedValue(new NotFoundException('Booking not found'));
      await expect(service.findInvoicesForBooking('bk-1')).rejects.toBeInstanceOf(
        NotFoundException,
      );
      expect(invoices.findForBooking).not.toHaveBeenCalled();
    });
  });
});
