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

namespace Nalu.Web.Data.Repositories;

public class SubscriptionRepository(MongoDbContext db)
{
    public async Task<Subscription?> FindByUserAsync(string userId, CancellationToken ct = default)
    {
        if (!db.IsConnected) return null;

        return await db.Subscriptions
            .Find(s => s.UserId == userId && s.Status == "active")
            .FirstOrDefaultAsync(ct);
    }

    public async Task<Subscription?> FindByStripeIdAsync(string stripeSubscriptionId, CancellationToken ct = default)
    {
        if (!db.IsConnected) return null;

        return await db.Subscriptions
            .Find(s => s.StripeSubscriptionId == stripeSubscriptionId)
            .FirstOrDefaultAsync(ct);
    }

    public async Task UpsertAsync(Subscription subscription, CancellationToken ct = default)
    {
        subscription.UpdatedAt = DateTime.UtcNow;

        await db.Subscriptions.ReplaceOneAsync(
            s => s.StripeSubscriptionId == subscription.StripeSubscriptionId,
            subscription,
            new ReplaceOptions { IsUpsert = true },
            ct);
    }

    public async Task UpdateStatusAsync(string stripeSubscriptionId, string status, CancellationToken ct = default)
    {
        await db.Subscriptions.UpdateOneAsync(
            s => s.StripeSubscriptionId == stripeSubscriptionId,
            Builders<Subscription>.Update
                .Set(s => s.Status, status)
                .Set(s => s.UpdatedAt, DateTime.UtcNow),
            cancellationToken: ct);
    }
}
