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

namespace OF_DL.Helpers;

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

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

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

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

            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 (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;
    }
}
