using Microsoft.EntityFrameworkCore;
using TakeoutSaaS.Domain.Tenants.Entities;
using TakeoutSaaS.Domain.Tenants.Enums;
using TakeoutSaaS.Domain.Tenants.Repositories;
using TakeoutSaaS.Infrastructure.App.Persistence;

namespace TakeoutSaaS.Infrastructure.App.Repositories;

/// <summary>
/// 租户配额使用仓储实现。
/// </summary>
public sealed class EfTenantQuotaUsageRepository(TakeoutAppDbContext context) : ITenantQuotaUsageRepository
{
    /// <inheritdoc />
    public Task<TenantQuotaUsage?> FindAsync(long tenantId, TenantQuotaType quotaType, CancellationToken cancellationToken = default)
    {
        return context.TenantQuotaUsages
            .FirstOrDefaultAsync(x => x.TenantId == tenantId && x.QuotaType == quotaType, cancellationToken);
    }

    /// <inheritdoc />
    public Task<IReadOnlyList<TenantQuotaUsage>> GetByTenantAsync(long tenantId, CancellationToken cancellationToken = default)
    {
        return context.TenantQuotaUsages
            .AsNoTracking()
            .Where(x => x.TenantId == tenantId)
            .OrderBy(x => x.QuotaType)
            .ToListAsync(cancellationToken)
            .ContinueWith(t => (IReadOnlyList<TenantQuotaUsage>)t.Result, cancellationToken);
    }

    /// <inheritdoc />
    public Task AddAsync(TenantQuotaUsage usage, CancellationToken cancellationToken = default)
    {
        return context.TenantQuotaUsages.AddAsync(usage, cancellationToken).AsTask();
    }

    /// <inheritdoc />
    public Task UpdateAsync(TenantQuotaUsage usage, CancellationToken cancellationToken = default)
    {
        context.TenantQuotaUsages.Update(usage);
        return Task.CompletedTask;
    }

    /// <inheritdoc />
    public Task SaveChangesAsync(CancellationToken cancellationToken = default)
    {
        return context.SaveChangesAsync(cancellationToken);
    }
}
