import { Test, TestingModule } from '@nestjs/testing';
import { getRepositoryToken } from '@nestjs/typeorm';
import { ClsService } from 'nestjs-cls';
import { BookingEntity } from '../../../entities/booking.entity';
import { MailerService } from '../../mailer/mailer.service';
import { MovementChartExportService } from './movement-chart-export.service';
import { DriverAssignmentService } from './driver-assignment.service';
import { MovementChartDigestService, localDay } from './movement-chart-digest.service';
import { CLS_TENANT_ID, CLS_USER_ID } from '../../../common/cls/cls.constants';

describe('localDay', () => {
  it('uses the Dubai calendar day, not UTC', () => {
    // 23:55 Dubai on 17 Oct = 19:55 UTC on 17 Oct; 01:00 Dubai on 18 Oct = 21:00 UTC on 17 Oct
    expect(localDay(new Date('2026-10-17T19:55:00Z'), 'Asia/Dubai', 1)).toBe('2026-10-18');
    expect(localDay(new Date('2026-10-17T21:00:00Z'), 'Asia/Dubai', 0)).toBe('2026-10-18');
    expect(localDay(new Date('2026-12-31T19:55:00Z'), 'Asia/Dubai', 3)).toBe('2027-01-03');
  });
});

describe('MovementChartDigestService', () => {
  let service: MovementChartDigestService;
  const query = jest.fn();
  const store = new Map<string, unknown>();
  const cls = {
    run: jest.fn((_opts: unknown, cb: () => unknown) => cb()),
    set: jest.fn((k: string, v: unknown) => store.set(k, v)),
  };
  const mailer = { send: jest.fn() };
  const mdExport = {
    buildWorkbook: jest
      .fn()
      .mockResolvedValue({ buffer: Buffer.from('xlsx'), filename: 'md.xlsx' }),
  };
  const driverAssignment = {
    getMovementChart: jest.fn().mockResolvedValue({
      by_booking: [{ ops: [{ type: 'transport', date: '2026-10-18', supplier_id: null }] }],
      by_activity: [{ items: [{ date: '2026-10-19', supplier_id: 's1' }] }],
    }),
  };

  beforeEach(async () => {
    const module: TestingModule = await Test.createTestingModule({
      providers: [
        MovementChartDigestService,
        { provide: getRepositoryToken(BookingEntity), useValue: { manager: { query } } },
        { provide: ClsService, useValue: cls },
        { provide: MailerService, useValue: mailer },
        { provide: MovementChartExportService, useValue: mdExport },
        { provide: DriverAssignmentService, useValue: driverAssignment },
      ],
    }).compile();
    service = module.get(MovementChartDigestService);
  });

  afterEach(() => {
    jest.clearAllMocks();
    store.clear();
  });

  const admin = {
    id: 'u1',
    name: 'Admin One',
    email: 'admin@example.com',
    role_id: 'r1',
    role_name: 'Admin',
    view_all: true,
  };

  it('mails the next 3 days with the Excel attached, acting as the tenant admin', async () => {
    query
      .mockResolvedValueOnce([admin, { ...admin, id: 'u2', email: 'two@example.com' }])
      .mockResolvedValueOnce([{ module: 'movement_chart', access_level: 'delete' }])
      .mockResolvedValueOnce([{ company_name: 'Mellow Tours' }]);
    const r = await service.sendForTenant('t1', new Date('2026-10-17T19:55:00Z'));
    expect(r).toEqual({ recipients: 2, from: '2026-10-18', to: '2026-10-20' });
    expect(store.get(CLS_TENANT_ID)).toBe('t1');
    expect(store.get(CLS_USER_ID)).toBe('u1');
    expect(mdExport.buildWorkbook).toHaveBeenCalledWith(undefined, '2026-10-18', '2026-10-20');
    const mail = mailer.send.mock.calls[0][0];
    expect(mail.to).toHaveLength(2);
    expect(mail.subject).toBe('Movement Dashboard 18/10/2026 – 20/10/2026');
    expect(mail.attachments).toEqual([{ name: 'md.xlsx', content: Buffer.from('xlsx') }]);
    expect(mail.fromName).toBe('Mellow Tours');
    expect(mail.html).toContain('18/10/2026');
  });

  it('skips a tenant with no active admin email', async () => {
    query.mockResolvedValueOnce([]);
    const r = await service.sendForTenant('t1', new Date('2026-10-17T19:55:00Z'));
    expect(r.recipients).toBe(0);
    expect(mailer.send).not.toHaveBeenCalled();
  });

  it('keeps going when one tenant fails', async () => {
    query
      .mockResolvedValueOnce([{ id: 't1' }, { id: 't2' }]) // tenants
      .mockRejectedValueOnce(new Error('db down')) // t1 admins
      .mockResolvedValueOnce([]); // t2 admins
    const r = await service.sendAllTenants(new Date('2026-10-17T19:55:00Z'));
    expect(r).toEqual({ sent: 0, skipped: 1, failed: 1 });
  });
});
