using HttpClientToCurl;
using HttpClientToCurl.Config;
using Microsoft.Extensions.Logging;
using System.Net.Http.Headers;

namespace Leanetec.EConnect.Infrastructure;

public static class LogExtensions
{
    public static void LogCurl(
        this ILogger logger,
        HttpClient client,
        HttpRequestMessage request,
        Action<StringConfig>? config = null,
        int maxLength = 1000,
        LogLevel logLevel = LogLevel.Information)
    {
        try
        {
            var curl = client.GenerateCurlInString(
                    request,
                    config
                    ).Truncate(maxLength);
            logger?.Log(logLevel, "{curl}", curl);
        }
        catch(Exception ex)
        {
            logger.LogError(ex, "An unexpected error occurred while logging the HTTP request as cURL.");
        }
    }

    public static void LogCurl(
        this ILogger logger,
        HttpClient client,
        HttpMethod method,
        string? uri = null,
        HttpRequestHeaders? headers = null,
        HttpContent? content = null,
        Action<StringConfig>? config = null,
        int maxLength = 1000,
        LogLevel logLevel = LogLevel.Information)
    {
        try
        {
            var curl = client.GenerateCurlInString(
                method,
                uri ?? "",
                headers,
                content,
                config
            ).Truncate(maxLength);
            logger?.Log(logLevel, "{curl}", curl);
        }
        catch (Exception ex)
        {
            logger.LogError(ex, "An unexpected error occurred while logging the HTTP request as cURL.");
        }
    }

    public static void LogCurl(
        this ILogger logger,
        HttpClient client,
        HttpMethod method,
        Uri uri,
        HttpRequestHeaders? headers = null,
        HttpContent? content = null,
        Action<StringConfig>? config = null,
        int maxLength = 1000,
        LogLevel logLevel = LogLevel.Information)
    {
        try
        {
            var curl = client.GenerateCurlInString(
                method,
                uri,
                headers,
                content,
                config
            ).Truncate(maxLength);
            logger?.Log(logLevel, "{curl}", curl);
        }
        catch (Exception ex)
        {
            logger.LogError(ex, "An unexpected error occurred while logging the HTTP request as cURL.");
        }
    }

    /// <summary>
    /// Truncates the string to the specified max length and appends a suffix if truncated.
    /// </summary>
    public static string Truncate(this string? value, int maxLength, string suffix = "...[truncated]")
    {
        if (string.IsNullOrEmpty(value) || maxLength <= 0)
            return string.Empty;

        return value.Length <= maxLength
            ? value
            : value[..maxLength] + suffix;
    }
}