using Newtonsoft.Json;
using OF_DL.Models.OfdlApi;
using Serilog;

namespace OF_DL.Helpers;

public static class VersionHelper
{
    private const string Url = "https://git.ofdl.tools/api/v1/repos/sim0n00ps/OF-DL/releases/latest";
    private static readonly HttpClient s_httpClient = new();

    public static async Task<string?> GetLatestReleaseTag(CancellationToken cancellationToken = default)
    {
        Log.Debug("Calling GetLatestReleaseTag");
        try
        {
            HttpResponseMessage response = await s_httpClient.GetAsync(Url, cancellationToken);

            if (!response.IsSuccessStatusCode)
            {
                Log.Debug("GetLatestReleaseTag did not return a Success Status Code");
                return null;
            }

            string body = await response.Content.ReadAsStringAsync(cancellationToken);

            Log.Debug("GetLatestReleaseTag API Response: {Body}", body);

            LatestReleaseApiResponse? versionCheckResponse =
                JsonConvert.DeserializeObject<LatestReleaseApiResponse>(body);

            if (versionCheckResponse != null && versionCheckResponse.TagName != "")
            {
                return versionCheckResponse.TagName;
            }

            Log.Debug("GetLatestReleaseTag did not return a valid tag name");
            return null;
        }
        catch (OperationCanceledException)
        {
            throw; // Rethrow timeout exceptions to be handled by the caller
        }
        catch (Exception ex)
        {
            Console.WriteLine("Exception caught: {0}\n\nStackTrace: {1}", ex.Message, ex.StackTrace);
            Log.Error("Exception caught: {0}\n\nStackTrace: {1}", ex.Message, ex.StackTrace);
            if (ex.InnerException != null)
            {
                Console.WriteLine("\nInner Exception:");
                Console.WriteLine("Exception caught: {0}\n\nStackTrace: {1}", ex.InnerException.Message,
                    ex.InnerException.StackTrace);
                Log.Error("Inner Exception: {0}\n\nStackTrace: {1}", ex.InnerException.Message,
                    ex.InnerException.StackTrace);
            }
        }

        return null;
    }
}
