using System.Text.Json;
using ScadaLink.Commons.Entities.Audit;
using ScadaLink.Commons.Interfaces.Services;

namespace ScadaLink.ConfigurationDatabase.Services;

public class AuditService : IAuditService
{
    private readonly ScadaLinkDbContext _context;

    public AuditService(ScadaLinkDbContext context)
    {
        _context = context ?? throw new ArgumentNullException(nameof(context));
    }

    public async Task LogAsync(
        string user,
        string action,
        string entityType,
        string entityId,
        string entityName,
        object? afterState,
        CancellationToken cancellationToken = default)
    {
        var entry = new AuditLogEntry(user, action, entityType, entityId, entityName)
        {
            Timestamp = DateTimeOffset.UtcNow,
            AfterStateJson = afterState != null
                ? JsonSerializer.Serialize(afterState)
                : null
        };

        // Add to change tracker only — caller is responsible for calling SaveChangesAsync
        // to ensure atomicity with the entity change.
        await _context.AuditLogEntries.AddAsync(entry, cancellationToken);
    }
}
