// Atomic Settlement Service Unit Tests

import { atomicSettlementService } from '@/core/settlement/isn/atomic-settlement.service';
import { createTestSovereignBank, createTestBankAccount, cleanDatabase } from '@/__tests__/utils/test-db';
import { testPrisma } from '@/__tests__/utils/test-db';

describe('AtomicSettlementService', () => {
  beforeEach(async () => {
    await cleanDatabase();
  });

  afterAll(async () => {
    await testPrisma.$disconnect();
  });

  describe('settleAtomically', () => {
    it('should settle multiple transactions atomically', async () => {
      const bank1 = await createTestSovereignBank({ sovereignCode: 'BANK1' });
      const bank2 = await createTestSovereignBank({ sovereignCode: 'BANK2' });

      const account1 = await createTestBankAccount({
        sovereignBankId: bank1.id,
        balance: '1000.00',
      });
      const account2 = await createTestBankAccount({
        sovereignBankId: bank2.id,
        balance: '500.00',
      });

      const result = await atomicSettlementService.settleAtomically({
        transactions: [
          {
            sourceAccountId: account1.id,
            destinationAccountId: account2.id,
            amount: '100.00',
            currencyCode: 'USD',
          },
        ],
        referenceId: 'ATOMIC-001',
      });

      expect(result.success).toBe(true);
      expect(result.settlementTime).toBeGreaterThan(0);
    });

    it('should rollback all transactions if any fails', async () => {
      const bank = await createTestSovereignBank();
      const account1 = await createTestBankAccount({
        sovereignBankId: bank.id,
        balance: '50.00', // Insufficient for 100.00 transfer
      });
      const account2 = await createTestBankAccount({
        sovereignBankId: bank.id,
      });

      await expect(
        atomicSettlementService.settleAtomically({
          transactions: [
            {
              sourceAccountId: account1.id,
              destinationAccountId: account2.id,
              amount: '100.00',
              currencyCode: 'USD',
            },
          ],
          referenceId: 'ATOMIC-002',
        })
      ).rejects.toThrow();

      // Verify no changes were made
      const updatedAccount1 = await testPrisma.bankAccount.findUnique({
        where: { id: account1.id },
      });
      expect(updatedAccount1?.balance.toString()).toBe('50.00');
    });
  });
});

