namespace AAIntegration.SimmonsBank.API.Controllers; using AutoMapper; using Microsoft.AspNetCore.Mvc; using Microsoft.Extensions.Options; using AAIntegration.SimmonsBank.API.Models.Accounts; using AAIntegration.SimmonsBank.API.Services; using AAIntegration.SimmonsBank.API.Config; using System.Collections.Generic; using AAIntegration.SimmonsBank.API.Entities; using Microsoft.AspNetCore.Authorization; using System.Security.Claims; [Authorize] [ApiController] [Route("[controller]")] public class AccountsController : ControllerBase { private IAccountService _accountService; private IUserService _userService; private IMapper _mapper; private readonly AppSettings _appSettings; private readonly ILogger _logger; public AccountsController( IAccountService accountService, IUserService userService, IMapper mapper, IOptions appSettings, ILogger logger) { _accountService = accountService; _userService = userService; _mapper = mapper; _appSettings = appSettings.Value; _logger = logger; } [HttpGet] public IActionResult GetAll() { List accountDtos = new List(); foreach (Account acc in _accountService.GetAll(GetCurrentUserId())) accountDtos.Add(_mapper.Map(acc)); return Ok(accountDtos); } [HttpGet("{id}")] public IActionResult GetById(int id) { Account account = _accountService.GetById(id, GetCurrentUserId()); return Ok(_mapper.Map(account)); } [HttpPost] public IActionResult Create([FromBody]AccountCreateRequest model) { _accountService.Create(model, GetCurrentUserId()); return Ok(new { message = "account created" }); } [HttpPut("{id}")] public IActionResult Update(int id, [FromBody]AccountUpdateRequest model) { _accountService.Update(id, model, GetCurrentUserId()); return Ok(new { message = "account updated" }); } [HttpDelete("{id}")] public IActionResult Delete(int id) { _accountService.Delete(id, GetCurrentUserId()); return Ok(new { message = "account deleted" }); } // Helpers private int GetCurrentUserId() { string apiKey = User.FindFirstValue(ClaimTypes.NameIdentifier); if (apiKey is null) _logger.LogInformation($"ApiKey: is null"); _logger.LogInformation($"apiKey: {apiKey}"); return _userService.GetUser(apiKey).Id; } }