import { BadRequestException, ForbiddenException } from '@nestjs/common';
import { Test } from '@nestjs/testing';
import { ClsService } from 'nestjs-cls';
import { CashHeldService } from './cash-held.service';
import { CashHeldRepository } from './repositories/cash-held.repository';
import { BankAccountService } from '../bank-account/bank-account.service';
import { AuditService } from '../audit/audit.service';
import { CLS_USER_PERMISSIONS } from '../../common/cls/cls.constants';
import { cashHolderKey } from './cash-holder';

describe('cashHolderKey', () => {
  it('treats own staff names case- and space-insensitively', () => {
    expect(cashHolderKey({ holder_type: 'OWN', collector_name: '  Ravi   Kumar ' })).toMatchObject({
      holder_key: 'OWN:ravi kumar',
      collector_name: 'Ravi Kumar',
    });
  });
  it('keys a supplier holder by supplier + driver', () => {
    expect(
      cashHolderKey({ holder_type: 'SUPPLIER', supplier_id: 's1', driver_id: 'd1' }).holder_key,
    ).toBe('SUPPLIER:s1:d1');
  });
  it('rejects a supplier holder without a driver', () => {
    expect(() => cashHolderKey({ holder_type: 'SUPPLIER', supplier_id: 's1' })).toThrow(
      BadRequestException,
    );
  });
});

describe('CashHeldService', () => {
  let service: CashHeldService;
  const em = { query: jest.fn(), getRepository: jest.fn(() => ({ update: jest.fn() })) };
  const repo = {
    manager: { query: jest.fn(), transaction: jest.fn((cb: (e: typeof em) => unknown) => cb(em)) },
    currentTenantId: jest.fn(() => 't1'),
    lockHolder: jest.fn(),
    balance: jest.fn(),
    insert: jest.fn((_em: unknown, row: Record<string, unknown>) =>
      Promise.resolve({ id: `m-${String(row.movement_type)}`, ...row }),
    ),
    history: jest.fn(),
    listHolders: jest.fn(),
  };
  const bankAccounts = { requireActive: jest.fn() };
  const audit = { log: jest.fn() };
  let perms: Record<string, string> = {};
  const cls = { get: jest.fn((k: string) => (k === CLS_USER_PERMISSIONS ? perms : null)) };

  const own = { holder_type: 'OWN' as const, collector_name: 'Ravi' };
  const base = { holder: own, currency_id: 'aed', date: '2026-10-20' };

  beforeEach(async () => {
    const module = await Test.createTestingModule({
      providers: [
        CashHeldService,
        { provide: CashHeldRepository, useValue: repo },
        { provide: BankAccountService, useValue: bankAccounts },
        { provide: AuditService, useValue: audit },
        { provide: ClsService, useValue: cls },
      ],
    }).compile();
    service = module.get(CashHeldService);
    perms = { cash_held: 'edit' };
  });

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

  it('refuses to spend more than the holder holds', async () => {
    repo.balance.mockResolvedValue(100);
    await expect(
      service.returnToOffice({ ...base, amount: 150, bank_account_id: 'b1' }),
    ).rejects.toThrow('Not enough cash held — available 100.00, needed 150.00');
    expect(repo.insert).not.toHaveBeenCalled();
  });

  it('locks the holder before reading the balance', async () => {
    repo.balance.mockResolvedValue(500);
    await service.returnToOffice({ ...base, amount: 200, bank_account_id: 'b1' });
    expect(repo.lockHolder.mock.invocationCallOrder[0]).toBeLessThan(
      repo.balance.mock.invocationCallOrder[0],
    );
    expect(repo.insert).toHaveBeenCalledWith(
      em,
      expect.objectContaining({ movement_type: 'RETURNED', direction: 'OUT', amount: 200 }),
    );
  });

  it('records a customer use against an existing booking', async () => {
    repo.manager.query.mockResolvedValueOnce([{ id: 'bk-1' }]);
    repo.balance.mockResolvedValue(500);
    await service.customerUse({ ...base, amount: 50, booking_id: 'bk-1', notes: 'Refund' });
    expect(repo.insert).toHaveBeenCalledWith(
      em,
      expect.objectContaining({ movement_type: 'CUSTOMER_USE', booking_id: 'bk-1' }),
    );
  });

  it('writes a paired out / in transfer', async () => {
    repo.balance.mockResolvedValue(500);
    await service.transfer({
      ...base,
      amount: 300,
      to_holder: { holder_type: 'OWN', collector_name: 'Ahmed' },
    });
    const types = repo.insert.mock.calls.map((c) => [c[1].movement_type, c[1].holder_key]);
    expect(types).toEqual([
      ['TRANSFER_OUT', 'OWN:ravi'],
      ['TRANSFER_IN', 'OWN:ahmed'],
    ]);
  });

  it('will not transfer to the same holder', async () => {
    await expect(
      service.transfer({
        ...base,
        amount: 10,
        to_holder: { holder_type: 'OWN', collector_name: 'RAVI' },
      }),
    ).rejects.toThrow(BadRequestException);
  });

  it('paying a supplier from held cash needs Cash Held → Edit', async () => {
    perms = { cash_held: 'view' };
    await expect(service.assertCanPayFromHeld(own, 'aed', 10)).rejects.toThrow(ForbiddenException);
  });

  it('history keeps a running balance and ignores pending receipts', async () => {
    repo.history.mockResolvedValue([
      { id: '1', direction: 'IN', amount: 1000 },
      { id: '2', direction: null, status: 'PENDING', amount: 400 },
      { id: '3', direction: 'OUT', amount: 250 },
    ]);
    const r = await service.history({ holder_key: 'OWN:ravi', currency_id: 'aed' });
    expect(r.events.map((e) => e.balance)).toEqual([1000, 1000, 750]);
    expect(r.balance).toBe(750);
  });
});

describe('Cash Held DTOs', () => {
  it('requires a purpose for customer use (no 500 on a missing note)', async () => {
    const { validate } = await import('class-validator');
    const { plainToInstance } = await import('class-transformer');
    const { CashHeldCustomerUseDto } = await import('./dto');
    const dto = plainToInstance(CashHeldCustomerUseDto, {
      holder: { holder_type: 'OWN', collector_name: 'Ravi' },
      currency_id: '11111111-1111-4111-8111-111111111111',
      amount: 5,
      date: '2026-10-20',
      booking_id: '11111111-1111-4111-8111-111111111111',
    });
    const errors = await validate(dto);
    expect(errors.map((e) => e.property)).toContain('notes');
  });
});
