import { BadRequestException } from '@nestjs/common';
import type { DataSource } from 'typeorm';

import { assertExportReceivedWithGrn } from './export-received-gate';

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

describe('assertExportReceivedWithGrn', () => {
  it('passes when the export booking has a received row with a GRN', async () => {
    await expect(
      assertExportReceivedWithGrn(db([{ '?column?': 1 }]), {
        id: 'b-1',
        tradeDirection: 'EXPORT',
      }),
    ).resolves.toBeUndefined();
  });

  it('rejects an export booking with nothing received', async () => {
    await expect(
      assertExportReceivedWithGrn(db([]), { id: 'b-1', tradeDirection: 'EXPORT' }),
    ).rejects.toBeInstanceOf(BadRequestException);
  });

  it('never blocks import — it loads off a train, not out of the warehouse', async () => {
    const source = db([]);
    await expect(
      assertExportReceivedWithGrn(source, { id: 'b-1', tradeDirection: 'IMPORT' }),
    ).resolves.toBeUndefined();
    // Import short-circuits before querying.
    expect((source.query as jest.Mock)).not.toHaveBeenCalled();
  });

  it('does not block intercity cargo', async () => {
    await expect(
      assertExportReceivedWithGrn(db([]), { id: 'b-1', tradeDirection: 'DOMESTIC' }),
    ).resolves.toBeUndefined();
  });
});
