using YMhut.Box.Core.Updates;

namespace YMhut.Box.WinUI.Services;

public interface IAppInstallerUpdateService
{
    Task<RemoteUpdateInfo?> GetUpdateInfoAsync(CancellationToken cancellationToken = default);

    Task<string?> DownloadUpdateAsync(
        RemoteUpdateInfo info,
        IProgress<UpdateDownloadProgress>? progress = null,
        CancellationToken cancellationToken = default);

    Task<string> CheckForUpdatesAsync(CancellationToken cancellationToken = default);
}

public sealed record RemoteUpdateInfo(
    string Version,
    string Build,
    string Channel,
    string Title,
    string Message,
    string ReleaseNotes,
    string DownloadUrl,
    string AppInstallerUrl,
    bool Mandatory,
    long SizeBytes,
    DateTimeOffset? PublishedAt,
    string MessageMarkdown = "",
    string ReleaseNotesMarkdown = "")
{
    public string EffectiveVersion => UpdateVersionComparer.NormalizeVersion(Version, Build);
    public string NormalizedVersion => EffectiveVersion;
    public string DisplayVersion => string.IsNullOrWhiteSpace(EffectiveVersion) ? Version : EffectiveVersion;
    public bool HasMarkdownNotes => !string.IsNullOrWhiteSpace(MessageMarkdown) || !string.IsNullOrWhiteSpace(ReleaseNotesMarkdown);
    public string DisplayMessage => string.IsNullOrWhiteSpace(MessageMarkdown) ? Message : MessageMarkdown;
    public string DisplayReleaseNotes => string.IsNullOrWhiteSpace(ReleaseNotesMarkdown) ? ReleaseNotes : ReleaseNotesMarkdown;

    public int CompareToCurrent(string currentVersion) => UpdateVersionComparer.Compare(Version, Build, currentVersion);

    public bool IsNewerThan(string currentVersion) => CompareToCurrent(currentVersion) > 0;
}

public sealed record UpdateDownloadProgress(
    long BytesReceived,
    long? TotalBytes,
    double BytesPerSecond)
{
    public double? Percentage => TotalBytes is > 0 ? BytesReceived * 100d / TotalBytes.Value : null;
}
