import * as ExcelJS from 'exceljs';
import { MovementChartExportService } from './movement-chart-export.service';

const transport = (over: Record<string, unknown>) => ({
  type: 'transport',
  booking_number: 'BK-1',
  guest_name: 'Guest One',
  guest_mobile: '+971500000001',
  adults: 2,
  children: 0,
  service_name: 'DXB Airport → Hotel',
  subtotal: 140,
  agent_name: 'Mellow Agent',
  price_currency_code: 'USD',
  actual_supplier_cost: 90,
  op_status: 'PLANNED',
  ...over,
});

const chart = {
  by_booking: [
    {
      ops: [
        transport({ id: 't1', date: '2026-10-21', time: '18:00' }),
        transport({ id: 't2', date: '2026-10-20', time: '09:00', booking_number: 'BK-2' }),
      ],
    },
  ],
  by_activity: [
    {
      items: [
        {
          id: 'a1',
          date: '2026-10-20',
          slot: '15:00',
          booking_number: 'BK-3',
          guest_name: 'Guest Three',
          activity_name: 'Desert Safari',
          adults: 2,
          children: 1,
          subtotal: 315,
          op_status: 'UNPLANNED',
        },
      ],
    },
  ],
  by_special: [
    {
      id: 's1',
      date: '2026-10-21',
      booking_number: 'BK-4',
      guest_name: 'Guest Four',
      service_name: 'Cake',
      total_price: 50,
    },
  ],
};

const getMovementChart = jest.fn().mockResolvedValue(chart);

async function build(
  sheets?: Array<'all' | 'transport' | 'activity' | 'special'>,
  canSeeCost = true,
  people?: { source_ids?: string[]; sales_user_ids?: string[] },
  columnGroups?: Array<'supplier' | 'driver' | 'cost' | 'messages'>,
) {
  const driverAssignment = { getMovementChart };
  const perms = { hasAtLeast: jest.fn().mockResolvedValue(canSeeCost) };
  const service = new MovementChartExportService(driverAssignment as never, perms as never);
  const { buffer } = await service.buildWorkbook(
    undefined,
    '2026-10-20',
    '2026-10-21',
    sheets,
    people,
    columnGroups,
  );
  const wb = new ExcelJS.Workbook();
  await wb.xlsx.load(buffer as unknown as ArrayBuffer);
  return wb;
}

/** Header → column index for a sheet. */
function columns(ws: ExcelJS.Worksheet): Record<string, number> {
  const out: Record<string, number> = {};
  ws.getRow(1).eachCell((c, i) => (out[String(c.value)] = i));
  return out;
}

describe('MovementChartExportService', () => {
  describe('buildWorkbook', () => {
    it('puts an All sheet first, followed by Transport / Activity / Special', async () => {
      const wb = await build();
      expect(wb.worksheets.map((w) => w.name)).toEqual(['All', 'Transport', 'Activity', 'Special']);
    });

    it('All sheet lists every movement in date then time order', async () => {
      const ws = (await build()).getWorksheet('All')!;
      const col = columns(ws);
      const rows = [2, 3, 4, 5].map((r) => ({
        type: ws.getRow(r).getCell(col['Type']).value,
        bill: ws.getRow(r).getCell(col['Bill No.']).value,
        time: ws.getRow(r).getCell(col['Time']).value,
      }));
      expect(rows).toEqual([
        { type: 'Transport', bill: 'BK-2', time: '9:00 AM' },
        { type: 'Activity', bill: 'BK-3', time: '3:00 PM' },
        // Special has no time — sorts first on its day.
        { type: 'Special', bill: 'BK-4', time: '' },
        { type: 'Transport', bill: 'BK-1', time: '6:00 PM' },
      ]);
      expect(ws.rowCount).toBe(5);
    });

    it('exports only the picked sheets', async () => {
      const wb = await build(['all', 'activity']);
      expect(wb.worksheets.map((w) => w.name)).toEqual(['All', 'Activity']);
      // All still covers every type even when the per-type sheets are off.
      expect(wb.getWorksheet('All')!.rowCount).toBe(5);
    });

    it('hides the Cost column without floor-pricing rights', async () => {
      const ws = (await build(['all'], false)).getWorksheet('All')!;
      expect(columns(ws)['Cost']).toBeUndefined();
    });

    it('keeps the original column order and adds Agent + Currency last', async () => {
      const wb = await build();
      const headers = (name: string) => {
        const out: string[] = [];
        wb.getWorksheet(name)!
          .getRow(1)
          .eachCell((c) => out.push(String(c.value)));
        return out;
      };
      expect(headers('All')).toEqual([
        'Date',
        'Time',
        'Type',
        'Bill No.',
        'Tour Type',
        'Guest Name',
        'Guest Number',
        'Adult',
        'Child',
        'Service',
        'Pickup Location',
        'Drop To',
        'Supplier',
        'Driver',
        'Vehicle Type',
        'Selling Price',
        'Cost',
        'Status',
        'Remarks',
        'Salesperson Name',
        'Agent',
        'Currency',
      ]);
      for (const ws of wb.worksheets) {
        const h: string[] = [];
        ws.getRow(1).eachCell((c) => h.push(String(c.value)));
        expect(h.slice(-2)).toEqual(['Agent', 'Currency']);
      }
      const all = wb.getWorksheet('All')!;
      const col = columns(all);
      // Row 2 = BK-2 transport.
      expect(all.getRow(2).getCell(col['Agent']).value).toBe('Mellow Agent');
      expect(all.getRow(2).getCell(col['Currency']).value).toBe('USD');
    });

    it('turns on the Excel header filter on each sheet', async () => {
      const wb = await build();
      for (const ws of wb.worksheets) expect(ws.autoFilter).toBeTruthy();
    });

    it('drops unticked column groups from every sheet', async () => {
      const wb = await build(undefined, true, undefined, ['supplier']);
      for (const ws of wb.worksheets) {
        const col = columns(ws);
        expect(col['Supplier']).toBeDefined();
        for (const h of [
          'Driver',
          'Vehicle Type',
          'Cost',
          'Actual Cost',
          'Customer Message',
          'Driver Message',
        ]) {
          expect(col[h]).toBeUndefined();
        }
      }
    });

    it('keeps every column when no groups are given (nightly email)', async () => {
      const col = columns((await build()).getWorksheet('Transport')!);
      for (const h of [
        'Supplier',
        'Driver',
        'Vehicle Type',
        'Cost',
        'Customer Message',
        'Driver Message',
      ]) {
        expect(col[h]).toBeDefined();
      }
    });

    it('never shows cost without floor-pricing rights, even when ticked', async () => {
      const wb = await build(undefined, false, undefined, ['cost']);
      for (const ws of wb.worksheets) {
        expect(columns(ws)['Cost']).toBeUndefined();
        expect(columns(ws)['Actual Cost']).toBeUndefined();
      }
    });

    it('passes agent / salesperson filters to the chart query', async () => {
      getMovementChart.mockClear();
      await build(['all'], true, { source_ids: ['src-1'], sales_user_ids: ['u-1'] });
      expect(getMovementChart).toHaveBeenCalledWith(undefined, '2026-10-20', {
        date_to: '2026-10-21',
        source_ids: ['src-1'],
        sales_user_ids: ['u-1'],
      });
    });
  });
});
