import { Test } from '@nestjs/testing';
import { getRepositoryToken } from '@nestjs/typeorm';
import { ClsService } from 'nestjs-cls';
import { AccountingService } from './accounting.service';
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 { CLS_TENANT_ID } from '../../common/cls/cls.constants';

// Customer invoice — client format (docs/invoice-format-plan.md).
describe('AccountingService — customer invoice', () => {
  let service: AccountingService;
  const managerQuery = jest.fn();
  const invoices = {
    save: jest.fn((x) => Promise.resolve({ id: 'inv-1', ...x })),
    findById: jest.fn(),
    // No invoice yet for the booking → a new one is issued.
    findLatestForBooking: jest.fn().mockResolvedValue(null),
    update: jest.fn(),
    manager: { query: managerQuery, findOne: jest.fn() },
  };
  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);
  });

  afterEach(() => jest.clearAllMocks());

  const booking = {
    id: 'bk-1',
    currency_id: 'aed',
    selling_currency_id: 'usd',
    exchange_rate: 0.27,
    selling_total: 0,
    grand_total: 500,
    guest_name: 'Mr. Karan',
    adults: 2,
    children_ages: [6],
    infants: 0,
    hotel_items: [],
    transport_items: [
      {
        id: 'tr-1',
        is_shared: false,
        quantity: 1,
        subtotal: 200,
        date: '2026-07-20',
        pickup_time: '08:55',
        transport_service: { from_city: 'Dubai', to_city: 'Abu Dhabi' },
        vehicle_type: { name: '7 Seater' },
      },
    ],
    activity_items: [
      {
        activity_id: 'a',
        ticket_id: null,
        date: '2026-07-23',
        age_group: 'adult',
        quantity: 2,
        subtotal: 200,
        activity: { name: 'Dubai Frame' },
      },
      {
        activity_id: 'a',
        ticket_id: null,
        date: '2026-07-23',
        age_group: 'child',
        quantity: 1,
        subtotal: 100,
        activity: { name: 'Dubai Frame' },
      },
    ],
    special_items: [],
    flight_details: [
      {
        transport_item_id: 'tr-1',
        airline: 'Emirates',
        flight_number: 'EK 565',
        origin_airport: 'BLR',
        destination_airport: 'DXB',
        departure_time: '2026-07-20T10:30',
        arrival_time: '2026-07-20T12:45',
      },
    ],
  };

  describe('generateCustomerInvoice', () => {
    beforeEach(() => {
      bookingService.findById.mockResolvedValue(booking);
      settingsRepo.findOne.mockResolvedValue({
        invoice_number_prefix: 'INV',
        invoice_number_padding: 6,
        invoice_number_reset: 'never',
        invoice_number_start: 60,
      });
      managerQuery.mockResolvedValue([{ last_number: 60 }]);
    });

    it('numbers the invoice from Invoice Settings', async () => {
      const inv = await service.generateCustomerInvoice({ booking_id: 'bk-1' });
      expect(inv.invoice_no).toBe('INV-000060');
    });

    it('prints activities as separate Adult and Child lines with real pax', async () => {
      const inv = await service.generateCustomerInvoice({ booking_id: 'bk-1' });
      const acts = inv.line_items!.filter((l) => l.kind === 'ACTIVITY');
      expect(acts.map((l) => [l.description, l.qty])).toEqual([
        ['Dubai Frame - Adult', 2],
        ['Dubai Frame - Child', 1],
      ]);
      expect(acts[0].details).toEqual(['Ticket Only', '23/07/2026']);
    });

    it('keeps each booking row of the same activity as its own line with its remarks', async () => {
      bookingService.findById.mockResolvedValue({
        ...booking,
        transport_items: [],
        activity_items: [
          {
            activity_id: 'm',
            ticket_id: 't',
            date: '2026-10-14',
            sort_order: 0,
            age_group: 'adult',
            quantity: 4,
            subtotal: 200,
            notes: 'Guest A - ORN1',
            activity: { name: 'Marina Dhow Cruise' },
            ticket: { name: 'Marina Dhow Cruise' },
          },
          {
            activity_id: 'g',
            ticket_id: null,
            date: '2026-10-14',
            sort_order: 1,
            age_group: 'adult',
            quantity: 2,
            subtotal: 20,
            notes: 'Guest B - TFF1',
            activity: { name: 'Grand mosque entry ticket' },
          },
          {
            activity_id: 'm',
            ticket_id: 't',
            date: '2026-10-14',
            sort_order: 2,
            age_group: 'child',
            quantity: 1,
            subtotal: 50,
            notes: 'Guest C - ORN2',
            activity: { name: 'Marina Dhow Cruise' },
            ticket: { name: 'Marina Dhow Cruise' },
          },
          {
            activity_id: 'm',
            ticket_id: 't',
            date: '2026-10-14',
            sort_order: 2,
            age_group: 'adult',
            quantity: 4,
            subtotal: 200,
            notes: 'Guest C - ORN2',
            activity: { name: 'Marina Dhow Cruise' },
            ticket: { name: 'Marina Dhow Cruise' },
          },
        ],
      });
      const inv = await service.generateCustomerInvoice({ booking_id: 'bk-1' });
      const acts = inv.line_items!.filter((l) => l.kind === 'ACTIVITY');
      expect(acts.map((l) => [l.description, l.qty, l.details?.[l.details.length - 1]])).toEqual([
        ['Marina Dhow Cruise - Adult', 4, 'Guest A - ORN1'],
        ['Grand mosque entry ticket - Adult', 2, 'Guest B - TFF1'],
        ['Marina Dhow Cruise - Adult', 4, 'Guest C - ORN2'],
        ['Marina Dhow Cruise - Child', 1, 'Guest C - ORN2'],
      ]);
    });

    it('prints transfers, activities and specials in the booking row order', async () => {
      bookingService.findById.mockResolvedValue({
        ...booking,
        flight_details: [],
        transport_items: [{ ...booking.transport_items[0], date: '2026-10-14', sort_order: 1 }],
        activity_items: [{ ...booking.activity_items[0], date: '2026-10-14', sort_order: 2 }],
        special_items: [
          { service_name: 'Cake', total_price: 10, date: '2026-10-14', sort_order: 0 },
        ],
      });
      const inv = await service.generateCustomerInvoice({ booking_id: 'bk-1' });
      expect(inv.line_items!.map((l) => l.kind)).toEqual(['SPECIAL', 'TRANSPORT', 'ACTIVITY']);
    });

    it('prints the transfer label, its subtotal and the linked flight', async () => {
      const inv = await service.generateCustomerInvoice({ booking_id: 'bk-1' });
      const tr = inv.line_items!.find((l) => l.kind === 'TRANSPORT')!;
      expect(tr.description).toBe('Dubai → Abu Dhabi');
      expect(tr.line_total).toBe(200);
      expect(tr.details).toEqual(
        expect.arrayContaining([
          'PVT - 7 Seater',
          'Emirates EK 565 (BLR - DXB) 10:30 AM - 12:45 PM',
          'Pickup time: 8:55 AM',
        ]),
      );
    });

    it('lists services in date order (activity on the 23rd after the 20th transfer)', async () => {
      const inv = await service.generateCustomerInvoice({ booking_id: 'bk-1' });
      expect(inv.line_items!.map((l) => l.kind)).toEqual(['TRANSPORT', 'ACTIVITY', 'ACTIVITY']);
      bookingService.findById.mockResolvedValueOnce({
        ...booking,
        transport_items: [{ ...booking.transport_items[0], date: '2026-07-25' }],
      });
      const later = await service.generateCustomerInvoice({ booking_id: 'bk-1' });
      expect(later.line_items!.map((l) => l.kind)).toEqual(['ACTIVITY', 'ACTIVITY', 'TRANSPORT']);
    });

    it('freezes the selling currency and exchange rate', async () => {
      const inv = await service.generateCustomerInvoice({ booking_id: 'bk-1' });
      expect(inv.selling_currency_id).toBe('usd');
      expect(inv.exchange_rate).toBe(0.27);
    });
  });

  describe('findInvoiceById — Bill To', () => {
    const inv = {
      id: 'inv-1',
      booking_id: 'bk-1',
      invoice_date: '2026-07-18',
      currency_id: 'aed',
      selling_currency_id: null,
      exchange_rate: null,
      guest_name_snapshot: 'Mr. Karan',
    };
    beforeEach(() => {
      invoices.findById.mockResolvedValue(inv);
      settingsRepo.findOne.mockResolvedValue({
        company_name: 'Mellow Tours LLC',
        invoice_due_days: 3,
      });
      bankAccounts.findInvoiceDefault.mockResolvedValue(null);
    });

    it('bills a B2B agency trip source', async () => {
      managerQuery.mockResolvedValueOnce([
        {
          booking_number: 'BK-1',
          source_type: 'B2B_AGENT',
          source_name: 'Navish',
          billing_name: 'NAVISH TRAVEL GROUP LLP',
          city: 'Ahmedabad',
          state: 'Gujarat',
          country: 'India',
          sales_team: [],
        },
      ]);
      const r = await service.findInvoiceById('inv-1');
      expect(r.print.bill_to).toMatchObject({ name: 'NAVISH TRAVEL GROUP LLP', state: 'Gujarat' });
      expect(r.print.reference).toBe('BK-1');
      expect(r.print.due_date).toBe('2026-07-21');
      expect(r.print.issuer.signatory).toBe('For, Mellow Tours LLC');
    });

    it('bills the agent for a quick (walk-in) booking made for a B2B agent', async () => {
      managerQuery.mockResolvedValueOnce([
        {
          booking_number: 'BK-2',
          source_type: 'B2B_AGENT',
          source_name: 'Luxury Journeys',
          billing_name: 'LUXURY JOURNEYS MANAGEMENT PVT LTD',
          is_walk_in: true,
          sales_team: [],
        },
      ]);
      const r = await service.findInvoiceById('inv-1');
      expect(r.print.bill_to.name).toBe('LUXURY JOURNEYS MANAGEMENT PVT LTD');
    });

    it('bills the guest for a direct source or no source', async () => {
      managerQuery
        .mockResolvedValueOnce([
          { booking_number: 'BK-6', source_type: 'DIRECT', source_name: 'Walking', sales_team: [] },
        ])
        .mockResolvedValueOnce([{ booking_number: 'BK-7', sales_team: [] }]);
      expect((await service.findInvoiceById('inv-1')).print.bill_to.name).toBe('Mr. Karan');
      expect((await service.findInvoiceById('inv-1')).print.bill_to.name).toBe('Mr. Karan');
    });

    it("never prints the destination's terms or the old tenant terms", async () => {
      settingsRepo.findOne.mockResolvedValue({ terms_and_conditions: 'Old tenant terms' });
      managerQuery.mockResolvedValueOnce([{ booking_number: 'BK-3', sales_team: [] }]);
      const r = await service.findInvoiceById('inv-1');
      expect(r.print.terms).toBeNull();
      expect(String(managerQuery.mock.calls[0][0])).not.toContain('terms_and_conditions');
    });

    it('prints no terms when Invoice Settings has none', async () => {
      settingsRepo.findOne.mockResolvedValue({ invoice_terms: '' });
      managerQuery.mockResolvedValueOnce([{ booking_number: 'BK-4', sales_team: [] }]);
      const r = await service.findInvoiceById('inv-1');
      expect(r.print.terms).toBeNull();
    });

    it("prints Invoice Settings' Payment Terms & Conditions", async () => {
      settingsRepo.findOne.mockResolvedValue({ invoice_terms: '<p>Pay in 7 days</p>' });
      managerQuery.mockResolvedValueOnce([{ booking_number: 'BK-5', sales_team: [] }]);
      const r = await service.findInvoiceById('inv-1');
      expect(r.print.terms).toBe('<p>Pay in 7 days</p>');
    });

    it('only reads the booking of the current tenant', async () => {
      managerQuery.mockResolvedValueOnce([]);
      await service.findInvoiceById('inv-1');
      expect(managerQuery.mock.calls[0][1].slice(0, 2)).toEqual(['bk-1', 't1']);
    });
  });
});

// AR aging on NET amounts — refund lines on an unpaid bill are price
// cuts (client 2026-10-20).
describe('AccountingService — getReceivablesAging', () => {
  let service: AccountingService;
  const query = 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: { manager: { query } } },
        { provide: getRepositoryToken(BookingTransportItemEntity), useValue: {} },
        { provide: getRepositoryToken(BookingActivityItemEntity), useValue: {} },
        { provide: getRepositoryToken(BookingSpecialItemEntity), useValue: {} },
        { provide: getRepositoryToken(TenantSettingsEntity), useValue: {} },
        { provide: CustomerInvoiceRepository, useValue: {} },
        { provide: BankAccountService, useValue: {} },
        { provide: BookingService, useValue: {} },
      ],
    }).compile();
    service = module.get(AccountingService);
  });

  afterEach(() => jest.clearAllMocks());

  const bk = (over: Record<string, string>) => ({
    guest_name: 'Guest',
    guest_mobile: '',
    currency_code: 'AED',
    current: '0',
    d_0_30: '0',
    d_31_60: '0',
    d_61_90: '0',
    d_90p: '0',
    refund_open: '0',
    ...over,
  });

  it('takes open refund lines off what the customer owes (BK-437675)', async () => {
    query.mockResolvedValue([
      bk({ booking_id: 'b1', guest_name: 'MR. TAUSIF', d_0_30: '5086', refund_open: '132' }),
    ]);
    const res = await service.getReceivablesAging({ as_of: '2026-10-20' });
    expect(res.rows).toHaveLength(1);
    expect(res.rows[0].total_outstanding).toBe(4954);
    expect(res.rows[0].d_0_30).toBe(4954);
    expect(res.totals.total_outstanding).toBe(4954);
  });

  it('cuts the newest bucket first', async () => {
    query.mockResolvedValue([
      bk({ booking_id: 'b1', current: '100', d_31_60: '500', refund_open: '150' }),
    ]);
    const { rows } = await service.getReceivablesAging({ as_of: '2026-10-20' });
    expect(rows[0]).toMatchObject({ current: 0, d_31_60: 450, total_outstanding: 450 });
  });

  it('drops a booking that owes nothing after the cut (real refund)', async () => {
    query.mockResolvedValue([
      bk({ booking_id: 'b1', current: '100', refund_open: '200' }),
      bk({ booking_id: 'b2', guest_name: 'Other', current: '300' }),
    ]);
    const { rows, totals } = await service.getReceivablesAging({ as_of: '2026-10-20' });
    expect(rows.map((r) => r.guest_name)).toEqual(['Other']);
    expect(totals.total_outstanding).toBe(300);
  });

  it('adds up several bookings of the same customer', async () => {
    query.mockResolvedValue([
      bk({
        booking_id: 'b1',
        guest_name: 'Nexus',
        guest_mobile: '92',
        d_0_30: '1560',
        refund_open: '1090',
      }),
      bk({ booking_id: 'b2', guest_name: 'Nexus', guest_mobile: '92', current: '320' }),
    ]);
    const { rows } = await service.getReceivablesAging({ as_of: '2026-10-20' });
    expect(rows).toHaveLength(1);
    expect(rows[0]).toMatchObject({ total_outstanding: 790, current: 320, d_0_30: 470 });
  });
});
