import { Test, TestingModule } from '@nestjs/testing';
import { getRepositoryToken } from '@nestjs/typeorm';
import { ClsService } from 'nestjs-cls';
import { ChangeRequestService } from './change-request.service';
import {
  BookingChangeRequestEntity,
  ChangeRequestStatus,
} from '../../entities/booking-change-request.entity';
import { BookingEntity } from '../../entities/booking.entity';
import { UserEntity } from '../../entities/user.entity';
import { BookingService } from '../booking/booking.service';
import { NotificationService } from '../notification/notification.service';
import { AuditService } from '../audit/audit.service';
import { DecideChangeRequestDto } from './dto/decide-change-request.dto';
import { ModuleName, AccessLevel } from '../../entities/role-permission.entity';
import { addDaysIso, todayInTz } from './booking-approval-triggers';

describe('ChangeRequestService', () => {
  let service: ChangeRequestService;
  const repo = {
    findOne: jest.fn(),
    update: jest.fn(),
    save: jest.fn(),
    find: jest.fn(),
    manager: { query: jest.fn().mockResolvedValue([]) },
  };
  const bookingRepo = {
    findOne: jest.fn().mockResolvedValue(null),
    manager: { query: jest.fn().mockResolvedValue([]) },
  };
  const bookingService = {
    applyApprovedChangeRequest: jest.fn(),
    validateChangeRequestPayload: jest.fn(),
    findById: jest.fn(),
  };
  const notifications = {
    create: jest.fn(),
    createForRoleWithAccess: jest.fn(),
    createForRolesWithAllAccess: jest.fn(),
  };
  const auditService = { log: jest.fn() };
  const cls = { get: jest.fn((k: string) => (k.includes('tenant') ? 'tenant-1' : 'user-1')) };

  const approve = {
    decision: 'approved',
    decision_remarks: 'Looks good — approve',
  } as unknown as DecideChangeRequestDto;
  const pendingRow = (over: Record<string, unknown> = {}) => ({
    id: 'cr-1',
    tenant_id: 'tenant-1',
    booking_id: 'booking-1',
    status: ChangeRequestStatus.PENDING,
    payload: { transport_items: [] },
    before_snapshot: { id: 'booking-1' },
    requester_id: null,
    ...over,
  });

  beforeEach(async () => {
    const module: TestingModule = await Test.createTestingModule({
      providers: [
        ChangeRequestService,
        { provide: getRepositoryToken(BookingChangeRequestEntity), useValue: repo },
        { provide: getRepositoryToken(BookingEntity), useValue: bookingRepo },
        { provide: getRepositoryToken(UserEntity), useValue: {} },
        { provide: ClsService, useValue: cls },
        { provide: BookingService, useValue: bookingService },
        { provide: NotificationService, useValue: notifications },
        { provide: AuditService, useValue: auditService },
      ],
    }).compile();
    service = module.get(ChangeRequestService);
    repo.update.mockResolvedValue({ affected: 1 });
  });

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

  // Option C (client 2026-10-30): an approver's edit waits as a
  // requester CR — nothing is applied until it is approved.
  describe('create', () => {
    const body = {
      kind: 'itinerary',
      requester_remarks: 'Add Crowne Plaza for the last night',
      payload: { hotel_items: [] },
    } as never;

    beforeEach(() => {
      bookingRepo.findOne.mockResolvedValueOnce({
        id: 'booking-1',
        booking_number: 'MT-1',
        status: 'upcoming',
        query: { start_date: '2099-01-01', destination: { timezone: 'Asia/Dubai' } },
      });
      bookingService.findById.mockResolvedValue({ id: 'booking-1', hotel_items: [] });
      repo.save.mockResolvedValue({ id: 'cr-new' });
    });

    it('stores a before snapshot and leaves the booking untouched', async () => {
      repo.findOne.mockResolvedValueOnce(null);
      const res = await service.create('booking-1', body);
      expect(repo.save).toHaveBeenCalledWith(
        expect.objectContaining({
          status: ChangeRequestStatus.PENDING,
          before_snapshot: { id: 'booking-1', hotel_items: [] },
        }),
      );
      expect(bookingService.applyApprovedChangeRequest).not.toHaveBeenCalled();
      expect(res.id).toBe('cr-new');
    });

    it('does not fold the edit into an old auto review notice', async () => {
      repo.findOne.mockResolvedValueOnce(null);
      await service.create('booking-1', body);
      expect(repo.findOne.mock.calls[0][0].where.before_snapshot).toBeDefined();
    });
  });

  // Next-day routing (client 2026-11-17): a change to today's /
  // tomorrow's plan goes to the ops approvers only.
  describe('create — next-day routing', () => {
    const tomorrow = addDaysIso(todayInTz('Asia/Dubai'), 1);
    const later = addDaysIso(todayInTz('Asia/Dubai'), 10);
    const snapshot = (date: string) => ({
      id: 'booking-1',
      transport_items: [{ id: 't1', date, pickup_time: '18:20:00' }],
    });
    const bodyFor = (date: string) =>
      ({
        kind: 'itinerary',
        requester_remarks: 'Flight delayed — move the pickup later please',
        payload: { transport_items: [{ id: 't1', date, pickup_time: '20:45' }] },
      }) as never;

    beforeEach(() => {
      bookingRepo.findOne.mockResolvedValueOnce({
        id: 'booking-1',
        booking_number: 'MT-1042',
        status: 'confirmed',
        query: { start_date: '2099-01-01', destination: { timezone: 'Asia/Dubai' } },
      });
      repo.findOne.mockResolvedValueOnce(null);
      repo.save.mockResolvedValue({ id: 'cr-new' });
    });

    it('notifies only booking-approval + movement-chart editors for tomorrow', async () => {
      bookingService.findById.mockResolvedValue(snapshot(tomorrow));
      await service.create('booking-1', bodyFor(tomorrow));
      expect(notifications.createForRoleWithAccess).not.toHaveBeenCalled();
      expect(notifications.createForRolesWithAllAccess).toHaveBeenCalledWith(
        [
          { module: ModuleName.BOOKING_APPROVAL, minLevel: AccessLevel.EDIT },
          { module: ModuleName.MOVEMENT_CHART, minLevel: AccessLevel.EDIT },
        ],
        expect.objectContaining({ title: 'Travels tomorrow — Change request — MT-1042' }),
        ['user-1'],
      );
    });

    it('keeps notifying every approver for later dates', async () => {
      bookingService.findById.mockResolvedValue(snapshot(later));
      await service.create('booking-1', bodyFor(later));
      expect(notifications.createForRolesWithAllAccess).not.toHaveBeenCalled();
      expect(notifications.createForRoleWithAccess).toHaveBeenCalledWith(
        ModuleName.BOOKING_APPROVAL,
        AccessLevel.EDIT,
        expect.objectContaining({ title: 'Change request — MT-1042' }),
        ['user-1'],
      );
    });
  });

  describe('create — price-only', () => {
    it('never alerts Ops for a price-only change, even on a running trip', async () => {
      const tomorrow = addDaysIso(todayInTz('Asia/Dubai'), 1);
      bookingRepo.findOne.mockResolvedValueOnce({
        id: 'booking-1',
        booking_number: 'MT-445375',
        status: 'ongoing',
        query: { start_date: '2026-01-01', destination: { timezone: 'Asia/Dubai' } },
      });
      repo.findOne.mockResolvedValueOnce(null);
      repo.save.mockResolvedValue({ id: 'cr-new' });
      const lines = [{ id: 't1', date: tomorrow, pickup_time: '17:00' }];
      bookingService.findById.mockResolvedValue({
        id: 'booking-1',
        markup_amount: 849,
        transport_items: lines,
      });
      await service.create('booking-1', {
        kind: 'itinerary',
        requester_remarks: 'Total package price corrected for the agent',
        payload: { markup_amount: 832, transport_items: lines },
      } as never);
      expect(notifications.createForRolesWithAllAccess).not.toHaveBeenCalled();
      expect(notifications.createForRoleWithAccess).toHaveBeenCalled();
    });
  });

  describe('findPending — travel info', () => {
    it('tags tomorrow requests and drops the loaded query', async () => {
      const tomorrow = addDaysIso(todayInTz('Asia/Dubai'), 1);
      repo.find.mockResolvedValueOnce([
        {
          ...pendingRow({
            before_snapshot: {
              transport_items: [{ id: 't1', date: tomorrow, pickup_time: '09:00' }],
            },
            payload: { transport_items: [] },
          }),
          booking: { id: 'booking-1', query: { destination: { timezone: 'Asia/Dubai' } } },
        },
        { ...pendingRow({ id: 'cr-2', booking_id: null, quote_id: 'q-1' }), booking: null },
      ]);
      const rows = await service.findPending();
      expect(rows.map((r) => r.travels_in_days)).toEqual([1, null]);
      expect(rows[0].first_change_date).toBe(tomorrow);
      expect(rows.map((r) => r.price_only)).toEqual([false, false]);
      expect((rows[0].booking as { query?: unknown }).query).toBeUndefined();
    });
  });

  describe('decide', () => {
    it('never touches the booking when a requester CR is rejected', async () => {
      repo.findOne.mockResolvedValueOnce(pendingRow());
      const res = await service.decide('cr-1', {
        decision: 'rejected',
        decision_remarks: 'Hotel not needed — keep as booked',
      } as unknown as DecideChangeRequestDto);
      expect(bookingService.applyApprovedChangeRequest).not.toHaveBeenCalled();
      expect(res.message).toContain('unchanged');
    });

    it('applies a requester CR on approval', async () => {
      repo.findOne.mockResolvedValueOnce(pendingRow());
      const res = await service.decide('cr-1', approve);
      expect(bookingService.applyApprovedChangeRequest).toHaveBeenCalledWith(
        'booking-1',
        { transport_items: [] },
        'cr-1',
      );
      expect(res.message).toContain('changes applied');
    });

    it('does not re-apply an auto review CR (H4)', async () => {
      repo.findOne.mockResolvedValueOnce(pendingRow({ before_snapshot: null }));
      const res = await service.decide('cr-1', approve);
      expect(bookingService.applyApprovedChangeRequest).not.toHaveBeenCalled();
      expect(res.message).toContain('already saved');
    });

    it('refuses when another decision already claimed it (C1)', async () => {
      repo.findOne.mockResolvedValueOnce(pendingRow());
      repo.update.mockResolvedValueOnce({ affected: 0 });
      await expect(service.decide('cr-1', approve)).rejects.toThrow('Already decided');
      expect(bookingService.applyApprovedChangeRequest).not.toHaveBeenCalled();
    });

    it('puts the CR back to pending when the apply fails', async () => {
      repo.findOne.mockResolvedValueOnce(pendingRow());
      bookingService.applyApprovedChangeRequest.mockRejectedValueOnce(new Error('on hold'));
      await expect(service.decide('cr-1', approve)).rejects.toThrow('on hold');
      expect(repo.update).toHaveBeenLastCalledWith(
        { id: 'cr-1', tenant_id: 'tenant-1' },
        expect.objectContaining({ status: ChangeRequestStatus.PENDING, decided_by: null }),
      );
    });
  });
});
