using System.Net.Http.Headers;
using System.Text.Json;
using DoliMiddlewareApi.Dtos.VeriFactu;

namespace DoliMiddlewareApi.Services.VeriFactu;

public class VeriFactuApiClient(HttpClient httpClient)
{
    private static readonly JsonSerializerOptions JsonOptions = new(JsonSerializerDefaults.Web);

    public string BaseUrl => httpClient.BaseAddress?.ToString() ?? "http://host.docker.internal:6789/";

    public Task<ProxyResponse> GetHealthAsync() => SendAsync(HttpMethod.Get, "api/v1/health");

    public Task<ProxyResponse> GetPublicKeyAsync() => SendAsync(HttpMethod.Get, "api/v1/auth/public-key");

    public Task<ProxyResponse> GetFormatsAsync() => SendAsync(HttpMethod.Get, "api/v1/formats");

    public async Task<ProxyResponse> RegisterCertificateAsync(RegisterCertificateDto dto)
    {
        var payload = new
        {
            cert_name = dto.CertName,
            cert_file = dto.CertFile,
            password_encrypted = dto.Password
        };

        return await SendAsync(HttpMethod.Post, "api/v1/auth/register", payload);
    }

    public Task<ProxyResponse> SendInvoiceAsync(JsonElement payload)
        => SendAsync(HttpMethod.Post, "api/v1/facturas", payload);

    public Task<ProxyResponse> CancelInvoiceAsync(JsonElement payload)
        => SendAsync(HttpMethod.Post, "api/v1/facturas/anular", payload);

    private async Task<ProxyResponse> SendAsync(HttpMethod method, string path, object? payload = null)
    {
        using var request = new HttpRequestMessage(method, path);

        if (payload is not null)
        {
            request.Content = JsonContent.Create(payload, options: JsonOptions);
        }

        using var response = await httpClient.SendAsync(request);
        var content = response.Content is null ? string.Empty : await response.Content.ReadAsStringAsync();
        var contentType = response.Content?.Headers.ContentType?.ToString() ?? "application/json";

        return new ProxyResponse((int)response.StatusCode, content, contentType);
    }
}