using Newtonsoft.Json;
using OF_DL.Entities;
using Serilog;

namespace OF_DL.Helpers;

public static class VersionHelper
{
    public static string? GetLatestReleaseTag()
    {
        Log.Debug("Calling GetLatestReleaseTag");
        try
        {
            HttpClient client = new();
            HttpRequestMessage request = new(HttpMethod.Get, "https://git.ofdl.tools/api/v1/repos/sim0n00ps/OF-DL/releases/latest");
            using var response = client.Send(request);

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

            var body = response.Content.ReadAsStringAsync().Result;

            Log.Debug("GetLatestReleaseTag API Response: ");
            Log.Debug(body);

            var versionCheckResponse = JsonConvert.DeserializeObject<LatestReleaseAPIResponse>(body);

            if (versionCheckResponse == null || versionCheckResponse.TagName == "")
            {
                Log.Debug("GetLatestReleaseTag did not return a valid tag name");
                return null;
            }

            return versionCheckResponse.TagName;
        }
        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;
    }
}
