using System.Text.Json;
using MemberCenter.Application.Abstractions;
using MemberCenter.Domain.Entities;
using MemberCenter.Infrastructure.Persistence;

namespace MemberCenter.Infrastructure.Services;

public sealed class AuditLogWriter : IAuditLogWriter
{
    private readonly MemberCenterDbContext _dbContext;

    public AuditLogWriter(MemberCenterDbContext dbContext)
    {
        _dbContext = dbContext;
    }

    public async Task WriteAsync(string actorType, Guid? actorId, string action, object payload)
    {
        _dbContext.AuditLogs.Add(new AuditLog
        {
            Id = Guid.NewGuid(),
            ActorType = actorType,
            ActorId = actorId,
            Action = action,
            Payload = JsonDocument.Parse(JsonSerializer.Serialize(payload))
        });
        await _dbContext.SaveChangesAsync();
    }
}
