using System.Text.Json; using DoliMiddlewareApi.Dtos.VeriFactu; using DoliMiddlewareApi.Services.VeriFactu; using Microsoft.AspNetCore.Authorization; using Microsoft.AspNetCore.Mvc; namespace DoliMiddlewareApi.Controllers; [ApiController] [Route("api/[controller]")] public class VeriFactuController(VeriFactuApiClient verifactuApiClient) : ControllerBase { [HttpGet("health")] [AllowAnonymous] public async Task Health() { try { var result = await verifactuApiClient.GetHealthAsync(); return Content(result.Content ?? "{\"status\":\"ok\"}", result.ContentType ?? "application/json"); } catch (HttpRequestException) { return Ok(new { status = "down", error = $"Connection refused ({verifactuApiClient.BaseUrl})", upstream = verifactuApiClient.BaseUrl }); } } [HttpGet("public-key")] [AllowAnonymous] public async Task PublicKey() { return await Proxy(verifactuApiClient.GetPublicKeyAsync()); } [HttpGet("formats")] [AllowAnonymous] public async Task Formats() { return await Proxy(verifactuApiClient.GetFormatsAsync()); } [HttpPost("certificates/register")] public async Task RegisterCertificate([FromBody] RegisterCertificateDto dto) { var logger = HttpContext.RequestServices.GetRequiredService>(); logger.LogInformation("[VeriFactuController] RegisterCertificate called. CertName={CertName}, CertFile length={CertFileLen}, Password length={PasswordLen}", dto.CertName, dto.CertFile?.Length ?? 0, dto.Password?.Length ?? 0); return await Proxy(verifactuApiClient.RegisterCertificateAsync(dto)); } [HttpPost("facturas")] public async Task SendInvoice([FromBody] JsonElement payload) { return await Proxy(verifactuApiClient.SendInvoiceAsync(payload)); } [HttpPost("facturas/anular")] public async Task CancelInvoice([FromBody] JsonElement payload) { return await Proxy(verifactuApiClient.CancelInvoiceAsync(payload)); } private async Task Proxy(Task task) { try { var result = await task; return new ContentResult { StatusCode = result.StatusCode, Content = result.Content, ContentType = result.ContentType }; } catch (HttpRequestException) { return StatusCode(StatusCodes.Status503ServiceUnavailable, new { title = "VeriFactu unavailable", status = 503, detail = $"No se puede conectar con VeriFactu en {verifactuApiClient.BaseUrl}" }); } } }