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<IActionResult> 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<IActionResult> PublicKey()
    {
        return await Proxy(verifactuApiClient.GetPublicKeyAsync());
    }

    [HttpGet("formats")]
    [AllowAnonymous]
    public async Task<IActionResult> Formats()
    {
        return await Proxy(verifactuApiClient.GetFormatsAsync());
    }

    [HttpPost("certificates/register")]
    public async Task<IActionResult> RegisterCertificate([FromBody] RegisterCertificateDto dto)
    {
        var logger = HttpContext.RequestServices.GetRequiredService<ILogger<VeriFactuController>>();
        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<IActionResult> SendInvoice([FromBody] JsonElement payload)
    {
        return await Proxy(verifactuApiClient.SendInvoiceAsync(payload));
    }

    [HttpPost("facturas/anular")]
    public async Task<IActionResult> CancelInvoice([FromBody] JsonElement payload)
    {
        return await Proxy(verifactuApiClient.CancelInvoiceAsync(payload));
    }

    private async Task<IActionResult> Proxy(Task<ProxyResponse> 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}"
            });
        }
    }
}