using ColaFlow.Shared.Kernel.Common;
using ColaFlow.Modules.ProjectManagement.Domain.ValueObjects;

namespace ColaFlow.Modules.ProjectManagement.Domain.Entities;

/// <summary>
/// AuditLog entity for tracking changes to entities (Create/Update/Delete operations)
/// Supports multi-tenant isolation and stores old/new values as JSON
/// </summary>
public class AuditLog : Entity
{
    public TenantId TenantId { get; private set; }
    public string EntityType { get; private set; }
    public Guid EntityId { get; private set; }
    public string Action { get; private set; } // "Create", "Update", "Delete"
    public UserId? UserId { get; private set; }
    public DateTime Timestamp { get; private set; }
    public string? OldValues { get; private set; } // JSONB - serialized old values
    public string? NewValues { get; private set; } // JSONB - serialized new values

    // EF Core constructor
    private AuditLog()
    {
        TenantId = null!;
        EntityType = null!;
        Action = null!;
    }

    /// <summary>
    /// Factory method to create a new AuditLog entry
    /// </summary>
    public static AuditLog Create(
        TenantId tenantId,
        string entityType,
        Guid entityId,
        string action,
        UserId? userId,
        string? oldValues,
        string? newValues)
    {
        if (string.IsNullOrWhiteSpace(entityType))
            throw new ArgumentException("Entity type cannot be empty", nameof(entityType));

        if (string.IsNullOrWhiteSpace(action))
            throw new ArgumentException("Action cannot be empty", nameof(action));

        return new AuditLog
        {
            Id = Guid.NewGuid(),
            TenantId = tenantId,
            EntityType = entityType,
            EntityId = entityId,
            Action = action,
            UserId = userId,
            Timestamp = DateTime.UtcNow,
            OldValues = oldValues,
            NewValues = newValues
        };
    }
}
