using MongoDB.Driver;
using Nalu.Web.Data.Models;

namespace Nalu.Web.Data.Repositories;

public class WebhookEventRepository(MongoDbContext db)
{
    /// <summary>
    /// Attempts to record a Stripe event for idempotency.
    /// Returns true if inserted (first time seen), false if already processed.
    /// </summary>
    public async Task<bool> TryInsertAsync(string stripeEventId, string eventType, CancellationToken ct = default)
    {
        if (!db.IsConnected) return true; // fallback: allow processing if DB unavailable

        try
        {
            await db.WebhookEvents.InsertOneAsync(new WebhookEvent
            {
                StripeEventId = stripeEventId,
                EventType = eventType
            }, cancellationToken: ct);

            return true;
        }
        catch (MongoWriteException ex) when (ex.WriteError.Category == ServerErrorCategory.DuplicateKey)
        {
            return false;
        }
    }

    public async Task<bool> ExistsAsync(string stripeEventId, CancellationToken ct = default)
    {
        if (!db.IsConnected) return false;

        return await db.WebhookEvents
            .Find(w => w.StripeEventId == stripeEventId)
            .AnyAsync(ct);
    }
}
