using System.Linq;

namespace Mlaumcherb.Client.Avalonia.сеть.Update;

public class Release
{
    [JsonRequired] public int id { get; set; }
    [JsonRequired] public string tag_name { get; set; } = "";
    [JsonRequired] public DateTime created_at { get; set; }
    // ReSharper disable once CollectionNeverUpdated.Global
    public List<Asset> assets { get; set; } = new();
    
    public class Asset
    {
        [JsonRequired] public int id { get; set; }
        [JsonRequired] public string name { get; set; } = "";
        [JsonRequired] public int size { get; set; }
        [JsonRequired] public DateTime created_at { get; set; }
        [JsonRequired] public string browser_download_url { get; set; } = "";

        public async Task Download(IOPath localPath)
        {
            await NetworkHelper.DownloadFile(browser_download_url, localPath);
        }
    }

    public Asset? FindAssetByName(string name) => 
        assets.FirstOrDefault(a => a.name == name);
}

public class GiteaClient(string ServerUrl)
{
    public async Task<Release> GetLatestRelease(string user, string repo)
    {
        string url = $"{ServerUrl}/api/v1/repos/{user}/{repo}/releases/latest";
        return await NetworkHelper.DownloadStringAndDeserialize<Release>(url);
    }
}