using Lib.Architecture.BuildingBlocks; using Microsoft.AspNetCore.Mvc; using Newtonsoft.Json; using Refit; namespace Core.Blueprint.API.Controllers { [Route("api/[controller]")] [ApiController] public class BaseController(ILogger logger) : ControllerBase { private readonly ILogger _logger = logger; protected Guid TrackingId => (Guid)(HttpContext.Items["TrackingId"] ?? Guid.NewGuid()); protected async Task Handle(Func>> apiCall) where T : class { var response = await apiCall().ConfigureAwait(false); _logger.LogInformation($"{TrackingId} - {response.RequestMessage?.Method} {response.RequestMessage?.RequestUri} - Status: {response.StatusCode}"); return FromAPIResponse(response); } private IActionResult FromAPIResponse(ApiResponse response) where T : class { if (response.IsSuccessful) return StatusCode((int)response.StatusCode, response.Content); else { dynamic errorContent = string.Empty; try { errorContent = JsonConvert.DeserializeObject(response.Error?.Content ?? string.Empty) ?? string.Empty; } catch (Exception) { errorContent = JsonConvert.DeserializeObject(response.Error?.Content); if (errorContent?.Error?.ErrorCode is null && errorContent?.Error?.Message is null && errorContent?.Error?.Target is null) errorContent = JsonConvert.DeserializeObject(response.Error?.Content); } return StatusCode((int)response.StatusCode, errorContent); } } } }