using Microsoft.EntityFrameworkCore;
using Tiku.Application.Commerce;
using Tiku.Domain.Commerce;

namespace Tiku.Infrastructure.Commerce;

public sealed partial class CommerceService
{
    public async Task<CurrentEntitlementItem> GetCurrentEntitlementAsync(
        CommerceActor actor,
        CancellationToken cancellationToken = default)
    {
        await AssertActiveMemberAsync(actor, cancellationToken);
        var now = DateTimeOffset.UtcNow;
        var entitlement = await dbContext.Entitlements
            .AsNoTracking()
            .Where(item =>
                item.TenantId == actor.TenantId &&
                item.UserId == actor.UserId &&
                item.EntitlementType == "svip" &&
                item.Status == EntitlementStatus.Active &&
                (item.ExpiresAt == null || item.ExpiresAt > now))
            .OrderByDescending(item => item.ExpiresAt)
            .FirstOrDefaultAsync(cancellationToken);

        if (entitlement is null) return new CurrentEntitlementItem(false, "svip", null, null, "inactive", null);

        return new CurrentEntitlementItem(
            true,
            entitlement.EntitlementType,
            entitlement.StartsAt,
            entitlement.ExpiresAt,
            entitlement.Status.ToString(),
            entitlement.ExpiresAt.HasValue
                ? Math.Max(0, (int)Math.Ceiling((entitlement.ExpiresAt.Value - now).TotalDays))
                : null);
    }
}