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

namespace TakeoutSaaS.Infrastructure.App.Persistence.Repositories;

/// <summary>
/// 租户可见角色规则仓储实现。
/// </summary>
public sealed class TenantVisibilityRoleRuleRepository(TakeoutAppDbContext context) : ITenantVisibilityRoleRuleRepository
{
    /// <summary>
    /// 按租户获取规则。
    /// </summary>
    /// <param name="tenantId">租户 ID。</param>
    /// <param name="cancellationToken">取消标记。</param>
    /// <returns>规则实体或 null。</returns>
    public Task<TenantVisibilityRoleRule?> FindByTenantIdAsync(long tenantId, CancellationToken cancellationToken = default)
    {
        return context.TenantVisibilityRoleRules
            .AsNoTracking()
            .FirstOrDefaultAsync(x => x.TenantId == tenantId && x.DeletedAt == null, cancellationToken);
    }

    /// <summary>
    /// 新增规则。
    /// </summary>
    /// <param name="rule">规则实体。</param>
    /// <param name="cancellationToken">取消标记。</param>
    /// <returns>异步任务。</returns>
    public Task AddAsync(TenantVisibilityRoleRule rule, CancellationToken cancellationToken = default)
    {
        return context.TenantVisibilityRoleRules.AddAsync(rule, cancellationToken).AsTask();
    }

    /// <summary>
    /// 更新规则。
    /// </summary>
    /// <param name="rule">规则实体。</param>
    /// <param name="cancellationToken">取消标记。</param>
    /// <returns>异步任务。</returns>
    public Task UpdateAsync(TenantVisibilityRoleRule rule, CancellationToken cancellationToken = default)
    {
        context.TenantVisibilityRoleRules.Update(rule);
        return Task.CompletedTask;
    }

    /// <summary>
    /// 保存变更。
    /// </summary>
    /// <param name="cancellationToken">取消标记。</param>
    /// <returns>异步任务。</returns>
    public Task SaveChangesAsync(CancellationToken cancellationToken = default)
    {
        return context.SaveChangesAsync(cancellationToken);
    }
}
