using System.Text.Json;
using CashLineERP.Domain.Integration;

namespace CashLineERP.Infrastructure.Persistence.Repositories;

internal static class OutboxEventWriter
{
    private static readonly JsonSerializerOptions JsonOptions = new(JsonSerializerDefaults.Web);

    public static OutboxEvent Enqueue(
        CashLineErpDbContext dbContext,
        string sourceModuleCode,
        string aggregateType,
        long aggregateId,
        string eventType,
        object payload,
        long? actorUserId,
        string? correlationKey = null)
    {
        var nextSequence = (dbContext.OutboxEvents.Max(entry => (long?)entry.Id) ?? 0L)
            + dbContext.ChangeTracker.Entries<OutboxEvent>().Count(entry => entry.State == Microsoft.EntityFrameworkCore.EntityState.Added)
            + 1L;

        var outboxEvent = new OutboxEvent(
            eventNumber: $"OUTBOX-{nextSequence:D6}",
            sourceModuleCode: sourceModuleCode.Trim().ToUpperInvariant(),
            aggregateType: aggregateType.Trim().ToUpperInvariant(),
            aggregateId: aggregateId,
            eventType: eventType.Trim().ToUpperInvariant(),
            correlationKey: correlationKey,
            payloadText: JsonSerializer.Serialize(payload, JsonOptions),
            availableAtUtc: DateTime.UtcNow);

        dbContext.OutboxEvents.Add(outboxEvent);
        return outboxEvent;
    }
}
