using System.IO;

namespace NexusShell.Services;

internal static class UpdateLogWriter
{
    private static readonly object Gate = new();
    private static string? _logPath;

    private static string LogPath
    {
        get
        {
            if (_logPath is not null)
            {
                return _logPath;
            }

            var dir = Path.Combine(
                Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData),
                "NinjaNexus",
                "logs");
            Directory.CreateDirectory(dir);
            _logPath = Path.Combine(dir, "update.log");
            return _logPath;
        }
    }

    public static void Info(string message) => Write("INFO", message);

    public static void Error(string message) => Write("ERROR", message);

    private static void Write(string level, string message)
    {
        var line = $"{DateTime.UtcNow:yyyy-MM-ddTHH:mm:ssZ} [{level}] {message}";
        lock (Gate)
        {
            try
            {
                File.AppendAllText(LogPath, line + Environment.NewLine);
            }
            catch
            {
                // Logging must not break update flow.
            }
        }
    }
}
