using System.Reflection;
using Microsoft.Extensions.Hosting;

namespace SpaceGame.Api.Shared.Runtime;

public sealed class AppVersionService
{
    private readonly VersionInfoSnapshot _snapshot;

    public AppVersionService(IHostEnvironment environment)
    {
        var assembly = Assembly.GetEntryAssembly() ?? Assembly.GetExecutingAssembly();
        var informationalVersion = assembly
            .GetCustomAttribute<AssemblyInformationalVersionAttribute>()?
            .InformationalVersion;
        var assemblyVersion = assembly.GetName().Version?.ToString() ?? "0.0.0";
        var version = string.IsNullOrWhiteSpace(informationalVersion) ? assemblyVersion : informationalVersion;
        var commitSha = Environment.GetEnvironmentVariable("SPACEGAME_COMMIT_SHA")
          ?? Environment.GetEnvironmentVariable("GIT_COMMIT_SHA");

        _snapshot = new VersionInfoSnapshot(
          version,
          environment.EnvironmentName,
          string.IsNullOrWhiteSpace(commitSha) ? null : commitSha,
          DateTimeOffset.UtcNow);
    }

    public VersionInfoSnapshot GetSnapshot() => _snapshot;
}
