// Settlement Workflow End-to-End Tests

import request from 'supertest';
import app from '@/integration/api-gateway/app';
import { createTestSovereignBank, createTestBankAccount, cleanDatabase } from '@/__tests__/utils/test-db';
import { testPrisma } from '@/__tests__/utils/test-db';
import { createAuthHeaders } from '@/__tests__/utils/test-auth';

describe('Settlement Workflow E2E', () => {
  beforeEach(async () => {
    await cleanDatabase();
  });

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

  it('should complete full settlement workflow', 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',
    });

    // Step 1: Initiate payment
    const paymentResponse = await request(app)
      .post('/api/payments')
      .set(createAuthHeaders({ sovereignBankId: bank1.id }))
      .send({
        debtorAccount: account1.accountNumber,
        creditorAccount: account2.accountNumber,
        amount: '100.00',
        currency: 'USD',
        priority: 'NORMAL',
        assetType: 'fiat',
      });

    expect([200, 201]).toContain(paymentResponse.status);
    const paymentId = paymentResponse.body.data?.paymentId;

    if (paymentId) {
      // Step 2: Check payment status
      const statusResponse = await request(app)
        .get(`/api/payments/${paymentId}`)
        .set(createAuthHeaders({ sovereignBankId: bank1.id }));

      expect(statusResponse.status).toBe(200);
      expect(statusResponse.body.data.status).toBe('settled');
    }

    // Step 3: Verify balances
    const updatedAccount1 = await testPrisma.bankAccount.findUnique({
      where: { id: account1.id },
    });
    const updatedAccount2 = await testPrisma.bankAccount.findUnique({
      where: { id: account2.id },
    });

    expect(updatedAccount1?.balance.toString()).toBe('900.00');
    expect(updatedAccount2?.balance.toString()).toBe('600.00');
  });
});

