using Microsoft.Extensions.Logging;
using DragonISO.App.Services;

namespace DragonISO.App;

// Background update check, throttled to once per 24h. Fire-and-forget
// so a slow / offline update server never delays startup. Surfaces a
// banner via UpdateBanner if newer; failures just log.
public partial class App
{
    /// <summary>
    /// Kick off the launch-time update check if the operator hasn't opted
    /// out via the flag file. Called from OnStartup right after the engine
    /// + view-model are live. Returns immediately; the actual HTTP call
    /// runs on a worker.
    /// </summary>
    private void StartBackgroundUpdateCheck(ILogger logger)
    {
        if (!UpdateChecker.LaunchCheckEnabled) return;
        if (_viewModel is null) return;

        var vm = _viewModel;
        _ = Task.Run(async () =>
        {
            try
            {
                var result = await UpdateChecker.CheckIfDueAsync(TimeSpan.FromHours(24));
                if (result?.Status == UpdateChecker.UpdateStatus.UpdateAvailable
                    && !string.IsNullOrEmpty(result.LatestTag)
                    && !string.IsNullOrEmpty(result.CurrentVersion))
                {
                    await Dispatcher.InvokeAsync(() =>
                        vm.UpdateBanner.Show(result.CurrentVersion!, result.LatestTag!));
                }
            }
            catch (Exception ex)
            {
                logger.LogDebug(ex, "Background update check failed");
            }
        });
    }
}
