import { ForbiddenException } from '@nestjs/common';
import {
  assertBookingOpen,
  assertPastBookingEditAllowed,
  assertSettlementNotHeld,
  canEditPastBookings,
  touchesMoney,
} from './booking-edit-guard';

const db = (rows: unknown[]) => ({ query: jest.fn().mockResolvedValue(rows) });

describe('assertBookingOpen', () => {
  it('passes an upcoming booking and a missing one', async () => {
    await expect(
      assertBookingOpen(db([{ booking_number: 'MT-1', status: 'upcoming' }]), 't', 'b'),
    ).resolves.toBeUndefined();
    await expect(assertBookingOpen(db([]), 't', 'b')).resolves.toBeUndefined();
  });

  it('rejects on hold and cancelled bookings', async () => {
    await expect(
      assertBookingOpen(db([{ booking_number: 'MT-1', status: 'on_hold' }]), 't', 'b'),
    ).rejects.toThrow('MT-1 is on hold');
    await expect(
      assertBookingOpen(db([{ booking_number: 'MT-1', status: 'cancelled' }]), 't', 'b'),
    ).rejects.toThrow('MT-1 is cancelled');
  });

  it('scopes the lookup to the tenant', async () => {
    const q = db([]);
    await assertBookingOpen(q, 'tenant-1', 'booking-1');
    expect(q.query).toHaveBeenCalledWith(expect.stringContaining('tenant_id = $2'), [
      'booking-1',
      'tenant-1',
    ]);
  });
});

describe('assertSettlementNotHeld', () => {
  it('passes when the settlement is not on HOLD', async () => {
    await expect(assertSettlementNotHeld(db([]), 't', 'b')).resolves.toBeUndefined();
  });

  it('rejects with the hold reason', async () => {
    await expect(
      assertSettlementNotHeld(db([{ hold_reason: 'disputed' }]), 't', 'b'),
    ).rejects.toThrow('on hold (disputed)');
  });
});

describe('touchesMoney', () => {
  it('is true for supplier / cost / pax and false for dispatch-only edits', () => {
    expect(touchesMoney({ actual_supplier_cost: 10 })).toBe(true);
    expect(touchesMoney({ supplier_id: null })).toBe(true);
    expect(touchesMoney({ adults_override: 2 })).toBe(true);
    expect(touchesMoney({ driver_id: 'd', pickup_time: '09:00', notes: 'x' })).toBe(false);
  });
});

describe('assertPastBookingEditAllowed', () => {
  const FUTURE = '2999-01-01';
  const PAST = '2000-01-01';
  const row = (status: string, end_date: string | null) => [
    { booking_number: 'MT-1', status, end_date },
  ];

  it('lets anyone edit a booking whose trip has not ended', async () => {
    await expect(
      assertPastBookingEditAllowed(db(row('upcoming', FUTURE)), 't', 'b', false),
    ).resolves.toBeUndefined();
    await expect(
      assertPastBookingEditAllowed(db(row('ongoing', null)), 't', 'b', false),
    ).resolves.toBeUndefined();
    await expect(assertPastBookingEditAllowed(db([]), 't', 'b', false)).resolves.toBeUndefined();
  });

  it('refuses an ended or completed booking without the permission', async () => {
    await expect(
      assertPastBookingEditAllowed(db(row('ongoing', PAST)), 't', 'b', false),
    ).rejects.toBeInstanceOf(ForbiddenException);
    await expect(
      assertPastBookingEditAllowed(db(row('completed', FUTURE)), 't', 'b', false),
    ).rejects.toThrow('MT-1 is a past booking');
  });

  it('allows them with the permission, without reading the booking', async () => {
    const q = db(row('completed', PAST));
    await expect(assertPastBookingEditAllowed(q, 't', 'b', true)).resolves.toBeUndefined();
    expect(q.query).not.toHaveBeenCalled();
  });

  it('filters by tenant', async () => {
    const q = db([]);
    await assertPastBookingEditAllowed(q, 'tenant-1', 'b', false);
    expect(q.query.mock.calls[0][1]).toEqual(['b', 'tenant-1']);
  });
});

describe('canEditPastBookings', () => {
  const cls = (permissions: Record<string, string> | null) => ({
    get: <T>() => permissions as T,
  });

  it('is on only at All (stored as delete)', () => {
    expect(canEditPastBookings(cls({ past_booking_edit: 'delete' }))).toBe(true);
    expect(canEditPastBookings(cls({ past_booking_edit: 'edit' }))).toBe(false);
    expect(canEditPastBookings(cls({ past_booking_edit: 'create' }))).toBe(false);
    expect(canEditPastBookings(cls({ past_booking_edit: 'view' }))).toBe(false);
    expect(canEditPastBookings(cls({ past_booking_edit: 'none' }))).toBe(false);
  });

  it('is false when the row is missing or Booking access is all the role has', () => {
    expect(canEditPastBookings(cls({ booking: 'delete' }))).toBe(false);
    expect(canEditPastBookings(cls(null))).toBe(false);
  });
});
