using System.Collections.Generic;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Logging;
namespace BankingApi.Controllers
public class TransactionController : Controller
public ILogger<TransactionController> logger;
public ITransactionService transactionService;
public IMongoCollection<TransactionLog> transactionLogCollection;
public TransactionController(ILogger<TransactionController> Logger, ITransactionService transactionService, IMongoClient mongoClient)
logger = Logger ?? throw new ArgumentNullException(nameof(Logger));
this.transactionService = transactionService ?? throw new ArgumentNullException(nameof(transactionService));
this.transactionLogCollection = mongoClient.GetDatabase("Banking").GetCollection<TransactionLog>("transactionLogs");
[HttpGet("account/{accountID}/transactions")]
public async Task<IActionResult> GetTransactions(string accountId)
if (string.IsNullOrWhiteSpace(accountId))
logger.LogError("Account ID is null or empty.");
return BadRequest("Account ID is required.");
if (ShouldLogTransactions())
logger.logdebug($"Transaction retrieval initiated for account ID: {accountId}");
LogTransactionAttempt(accountId);
var transactions = await transactionService.GetTransactionsByAccountId(accountId);
logger.LogWarning($"No transactions found for account ID: {accountId}");
return NotFound("No transactions found for account ID {accountId}.");
logger.LogError(ex, "Error occurred while retrieving transactions.");
return StatusCode(500, "An internal error occurred.");
private bool ShouldLogTransactions()
string logTransactions = Environment.GetEnvironmentVariable("LOG_TRANSACTIONS");
return bool.TryParse(logTransactions, out bool shouldLog) && shouldLog;
private void LogTransactionAttempt(string accountId)
var transactionLog = new TransactionLog
Message = "Transaction retrieval attempted"
transactionLogCollection.InsertOne(transactionLog);
public class TransactionLog
public string AccountId { get; set; }
public DateTime Date { get; set; }
public string Message { get; set; }