using Microsoft.EntityFrameworkCore;
using TakeoutSaaS.Domain.Dictionary.Entities;
using TakeoutSaaS.Domain.Dictionary.Repositories;
using TakeoutSaaS.Infrastructure.Dictionary.Persistence;

namespace TakeoutSaaS.Infrastructure.Dictionary.Repositories;

/// <summary>
/// 租户字典覆盖仓储实现。
/// </summary>
public sealed class TenantDictionaryOverrideRepository(DictionaryDbContext context) : ITenantDictionaryOverrideRepository
{
    /// <summary>
    /// 获取租户覆盖配置。
    /// </summary>
    public Task<TenantDictionaryOverride?> GetAsync(long tenantId, long systemGroupId, CancellationToken cancellationToken = default)
    {
        return context.TenantDictionaryOverrides
            .FirstOrDefaultAsync(config =>
                config.TenantId == tenantId &&
                config.SystemDictionaryGroupId == systemGroupId &&
                config.DeletedAt == null,
                cancellationToken);
    }

    /// <summary>
    /// 获取租户全部覆盖配置。
    /// </summary>
    public async Task<IReadOnlyList<TenantDictionaryOverride>> ListAsync(long tenantId, CancellationToken cancellationToken = default)
    {
        return await context.TenantDictionaryOverrides
            .AsNoTracking()
            .Where(config => config.TenantId == tenantId && config.DeletedAt == null)
            .ToListAsync(cancellationToken);
    }

    /// <summary>
    /// 新增覆盖配置。
    /// </summary>
    public Task AddAsync(TenantDictionaryOverride overrideConfig, CancellationToken cancellationToken = default)
    {
        context.TenantDictionaryOverrides.Add(overrideConfig);
        return Task.CompletedTask;
    }

    /// <summary>
    /// 更新覆盖配置。
    /// </summary>
    public Task UpdateAsync(TenantDictionaryOverride overrideConfig, CancellationToken cancellationToken = default)
    {
        context.TenantDictionaryOverrides.Update(overrideConfig);
        return Task.CompletedTask;
    }

    /// <summary>
    /// 持久化更改。
    /// </summary>
    public Task SaveChangesAsync(CancellationToken cancellationToken = default)
        => context.SaveChangesAsync(cancellationToken);
}
