using e_suite.Database.Audit.Tables.Audit;
using eSuite.Core.Clock;
using Microsoft.EntityFrameworkCore.ChangeTracking;
using Newtonsoft.Json;

namespace e_suite.Database.Audit.AuditEngine;

public class AuditRecorder
{
    private readonly IClock _clock;

    public AuditRecorder(EntityEntry? entry, AuditUserDetails auditUserDetails, IClock clock)
    {
        _clock = clock;
        Entry = entry;
        UserId = auditUserDetails.UserId;
        UserDisplayName = auditUserDetails.UserDisplayName;
        Comment = auditUserDetails.Comment;
    }
    public EntityEntry? Entry { get; }
    public long UserId { get; set; }
    public string UserDisplayName { get; set; }
    public Dictionary<string, Change> Fields { get; } = [];
    public AuditDrillUp DrillUp { get; set; } = null!;
    public AuditType AuditType { get; set; }
    public string Comment { get; set; }

    public AuditDetail ToAudit()
    {
        var audit = new AuditDetail
        {
            UserId = UserId,
            UserDisplayName = UserDisplayName,
            Type = AuditType.ToString(),
            Comment = Comment,
            DateTime = _clock.GetNow,
            Fields = Fields.Count == 0 ? string.Empty : JsonConvert.SerializeObject(Fields, new JsonSerializerSettings
            {
                NullValueHandling = NullValueHandling.Ignore
            })
        };
        return audit;
    }
}