
/**
 * Task 4: Validation Service
 */
export function validateTransactionAndAccounts({ financialTransaction, debitAccount, creditAccount }) {
  const errors = [];

  if (!financialTransaction) {
    return { valid: false, errors: ['Transaction is missing'] };
  }

  if (!financialTransaction.amount || financialTransaction.amount <= 0) {
    errors.push(`Amount must be greater than zero. Got: ${financialTransaction.amount}`);
  }

  if (!debitAccount) {
    errors.push('Debit account is missing or could not be resolved.');
  } else if (!debitAccount.is_active) {
    errors.push(`Debit account ${debitAccount.account_name} is inactive.`);
  }

  if (!creditAccount) {
    errors.push('Credit account is missing or could not be resolved.');
  } else if (!creditAccount.is_active) {
    errors.push(`Credit account ${creditAccount.account_name} is inactive.`);
  }

  if (debitAccount && creditAccount && debitAccount.id === creditAccount.id) {
    errors.push('Debit and credit accounts cannot be the same.');
  }

  // Cross-client check
  if (debitAccount && debitAccount.client_id !== financialTransaction.client_id) {
    errors.push('Debit account does not belong to the transaction client.');
  }
  if (creditAccount && creditAccount.client_id !== financialTransaction.client_id) {
    errors.push('Credit account does not belong to the transaction client.');
  }

  return {
    valid: errors.length === 0,
    errors
  };
}
