// Test Database Utilities
// Helpers for database operations in tests

import { PrismaClient } from '@prisma/client';
import { Decimal } from '@prisma/client/runtime/library';

const testPrisma = new PrismaClient({
  datasources: {
    db: {
      url: process.env.TEST_DATABASE_URL || 'postgresql://test:test@localhost:5432/dbis_test',
    },
  },
});

/**
 * Clean database before each test
 */
export async function cleanDatabase(): Promise<void> {
  // Delete in reverse order of dependencies
  const tables = [
    'LedgerEntry',
    'BankAccount',
    'SovereignIdentity',
    'SovereignBank',
  ];

  for (const table of tables) {
    await (testPrisma as any)[table].deleteMany({});
  }
}

/**
 * Create a test sovereign bank
 */
export async function createTestSovereignBank(data?: {
  sovereignCode?: string;
  name?: string;
  bic?: string;
}) {
  return await testPrisma.sovereignBank.create({
    data: {
      sovereignCode: data?.sovereignCode || 'TEST',
      name: data?.name || 'Test Bank',
      bic: data?.bic || 'TESTXXXX',
      status: 'active',
    },
  });
}

/**
 * Create a test bank account
 */
export async function createTestBankAccount(data: {
  sovereignBankId: string;
  accountNumber?: string;
  accountType?: string;
  currencyCode?: string;
  balance?: string;
}) {
  return await testPrisma.bankAccount.create({
    data: {
      accountNumber: data.accountNumber || `ACC-${Date.now()}`,
      sovereignBankId: data.sovereignBankId,
      accountType: data.accountType || 'commercial',
      currencyCode: data.currencyCode || 'USD',
      balance: new Decimal(data.balance || '0'),
      availableBalance: new Decimal(data.balance || '0'),
      reservedBalance: new Decimal('0'),
      status: 'active',
    },
  });
}

/**
 * Rollback transaction wrapper for tests
 */
export async function withTransaction<T>(
  callback: (tx: PrismaClient) => Promise<T>
): Promise<T> {
  return await testPrisma.$transaction(async (tx) => {
    return await callback(tx as PrismaClient);
  });
}

export { testPrisma };

