import { BadRequestException } from '@nestjs/common';
import { BookingItineraryService } from './booking-itinerary.service';
import type { UpdateBookingDto } from '../dto/update-booking.dto';

/**
 * Completed / No-show / Cancelled rows are locked for normal saves, but an
 * approved change request may still change them (MT-843032: the rows went
 * Completed on the Movement Dashboard while the request waited, and
 * approving failed for good). Removal stays blocked either way.
 */
describe('BookingItineraryService — locked rows', () => {
  const lockedActivity = {
    id: 'a1',
    tenant_id: 't1',
    op_status: 'PICKED_UP',
    activity_id: 'act-1',
    quantity: 2,
    unit_price: 100,
    date: '2026-11-24',
  };
  const lockedTransfer = {
    id: 'tr1',
    tenant_id: 't1',
    op_status: 'NO_SHOW',
    transport_service_id: 'ts-1',
    quantity: 1,
    unit_price: 200,
    date: '2026-11-24',
  };

  let activityFind: jest.Mock;
  let transportFind: jest.Mock;
  let check: (dto: UpdateBookingDto, allowChanges?: boolean) => Promise<void>;

  beforeEach(() => {
    activityFind = jest.fn().mockResolvedValue([lockedActivity]);
    transportFind = jest.fn().mockResolvedValue([lockedTransfer]);
    const service = Object.create(BookingItineraryService.prototype) as Record<string, unknown>;
    service.activityItemRepo = { find: activityFind };
    service.transportItemRepo = { find: transportFind };
    const fn = service.assertLockedRowsUnchanged as (
      bookingId: string,
      tenantId: string,
      dto: UpdateBookingDto,
      allowChanges?: boolean,
    ) => Promise<void>;
    check = (dto, allowChanges) => fn.call(service, 'b1', 't1', dto, allowChanges);
  });

  const movedActivity = { activity_items: [{ ...lockedActivity, date: '2026-11-19' }] };
  const swappedTransfer = {
    transport_items: [{ ...lockedTransfer, transport_service_id: 'ts-2' }],
  };

  it('blocks a normal save that changes a locked activity or transfer', async () => {
    await expect(check(movedActivity as unknown as UpdateBookingDto)).rejects.toThrow(
      BadRequestException,
    );
    await expect(check(swappedTransfer as unknown as UpdateBookingDto)).rejects.toThrow(
      "A Completed / No-show / Cancelled transfer can't be changed",
    );
  });

  it('lets an approved change request change locked rows', async () => {
    await expect(
      check(movedActivity as unknown as UpdateBookingDto, true),
    ).resolves.toBeUndefined();
    await expect(
      check(swappedTransfer as unknown as UpdateBookingDto, true),
    ).resolves.toBeUndefined();
  });

  it('still blocks removing a locked row, even on approval', async () => {
    const dto = { activity_items: [{ id: 'other', activity_id: 'act-2', quantity: 1 }] };
    await expect(check(dto as unknown as UpdateBookingDto, true)).rejects.toThrow(
      "A Completed / No-show / Cancelled activity can't be removed",
    );
  });

  it('only reads rows of the current tenant and booking', async () => {
    await check(movedActivity as unknown as UpdateBookingDto, true);
    expect(activityFind).toHaveBeenCalledWith({
      where: { booking_id: 'b1', tenant_id: 't1', is_deleted: false },
    });
  });
});
