using System.Diagnostics;
using System.IO;
using System.Text.Json;
using NexusShell.Models;

namespace NexusShell.Services;

public sealed class NexusConsoleAuditService
{
    private readonly string _auditFilePath;
    private readonly object _lock = new();

    public NexusConsoleAuditService()
    {
        _auditFilePath = Path.Combine(
            Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData),
            "NinjaNexus",
            "audit",
            "nexus-console-audit.jsonl");

        Directory.CreateDirectory(Path.GetDirectoryName(_auditFilePath)!);
    }

    public string AuditFilePath => _auditFilePath;

    public void Log(string user, string role, string command, string result, bool allowed)
    {
        var entry = new NexusConsoleAuditEntry
        {
            Timestamp = DateTimeOffset.UtcNow,
            User = user,
            Role = role,
            Command = command,
            Result = result,
            Allowed = allowed,
        };

        lock (_lock)
        {
            try
            {
                var line = JsonSerializer.Serialize(entry, JsonOptions);
                File.AppendAllText(_auditFilePath, line + Environment.NewLine);
            }
            catch (Exception ex)
            {
                Debug.WriteLine($"[Nexus Console] audit persist failed: {ex.Message}");
            }
        }
    }

    private static readonly JsonSerializerOptions JsonOptions = new()
    {
        PropertyNamingPolicy = JsonNamingPolicy.CamelCase,
    };
}
