using Microsoft.EntityFrameworkCore;
using TakeoutSaaS.Domain.Identity.Entities;
using TakeoutSaaS.Domain.Identity.Enums;
using TakeoutSaaS.Domain.Identity.Repositories;

namespace TakeoutSaaS.Infrastructure.Identity.Persistence;

/// <summary>
/// EF 权限仓储。
/// </summary>
public sealed class EfPermissionRepository(IdentityDbContext dbContext) : IPermissionRepository
{
    /// <summary>
    /// 根据权限 ID 获取权限。
    /// </summary>
    /// <param name="permissionId">权限 ID。</param>
    /// <param name="cancellationToken">取消标记。</param>
    /// <returns>权限实体或 null。</returns>
    public Task<Permission?> FindByIdAsync(long permissionId, CancellationToken cancellationToken = default)
        => dbContext.Permissions
            .IgnoreQueryFilters()
            .AsNoTracking()
            .FirstOrDefaultAsync(x => x.Id == permissionId && x.DeletedAt == null, cancellationToken);

    /// <summary>
    /// 根据权限编码获取权限。
    /// </summary>
    /// <param name="code">权限编码。</param>
    /// <param name="cancellationToken">取消标记。</param>
    /// <returns>权限实体或 null。</returns>
    public Task<Permission?> FindByCodeAsync(string code, CancellationToken cancellationToken = default)
        => dbContext.Permissions
            .IgnoreQueryFilters()
            .AsNoTracking()
            .FirstOrDefaultAsync(x => x.Code == code && x.DeletedAt == null, cancellationToken);

    /// <summary>
    /// 根据权限编码集合批量获取权限。
    /// </summary>
    /// <param name="codes">权限编码集合。</param>
    /// <param name="cancellationToken">取消标记。</param>
    /// <returns>权限列表。</returns>
    public Task<IReadOnlyList<Permission>> GetByCodesAsync(IEnumerable<string> codes, CancellationToken cancellationToken = default)
    {
        // 1. 规范化编码集合
        var normalizedCodes = codes
            .Where(code => !string.IsNullOrWhiteSpace(code))
            .Select(code => code.Trim())
            .Distinct()
            .ToArray();

        // 2. 读取全局权限（已固定）
        return dbContext.Permissions
            .IgnoreQueryFilters()
            .AsNoTracking()
            .Where(x => x.DeletedAt == null && normalizedCodes.Contains(x.Code))
            .ToListAsync(cancellationToken)
            .ContinueWith(t => (IReadOnlyList<Permission>)t.Result, cancellationToken);
    }

    /// <summary>
    /// 根据权限 ID 集合批量获取权限。
    /// </summary>
    /// <param name="permissionIds">权限 ID 集合。</param>
    /// <param name="cancellationToken">取消标记。</param>
    /// <returns>权限列表。</returns>
    public Task<IReadOnlyList<Permission>> GetByIdsAsync(IEnumerable<long> permissionIds, CancellationToken cancellationToken = default)
        => dbContext.Permissions
            .IgnoreQueryFilters()
            .AsNoTracking()
            .Where(x => x.DeletedAt == null && permissionIds.Contains(x.Id))
            .ToListAsync(cancellationToken)
            .ContinueWith(t => (IReadOnlyList<Permission>)t.Result, cancellationToken);

    /// <summary>
    /// 按 Portal 与关键字搜索权限。
    /// </summary>
    /// <param name="portal">Portal 类型。</param>
    /// <param name="keyword">搜索关键字。</param>
    /// <param name="cancellationToken">取消标记。</param>
    /// <returns>权限列表。</returns>
    public Task<IReadOnlyList<Permission>> SearchAsync(PortalType portal, string? keyword, CancellationToken cancellationToken = default)
    {
        // 1. 构建基础查询
        var query = dbContext.Permissions
            .IgnoreQueryFilters()
            .AsNoTracking()
            .Where(x => x.DeletedAt == null && x.Portal == portal);
        if (!string.IsNullOrWhiteSpace(keyword))
        {
            // 2. 追加关键字过滤
            var normalized = keyword.Trim();
            query = query.Where(x => x.Name.Contains(normalized) || x.Code.Contains(normalized));
        }

        // 3. 返回列表
        return query.ToListAsync(cancellationToken)
            .ContinueWith(t => (IReadOnlyList<Permission>)t.Result, cancellationToken);
    }

    /// <summary>
    /// 新增权限。
    /// </summary>
    /// <param name="permission">权限实体。</param>
    /// <param name="cancellationToken">取消标记。</param>
    /// <returns>异步任务。</returns>
    public Task AddAsync(Permission permission, CancellationToken cancellationToken = default)
    {
        // 1. 添加实体
        dbContext.Permissions.Add(permission);
        // 2. 返回完成任务
        return Task.CompletedTask;
    }

    /// <summary>
    /// 更新权限。
    /// </summary>
    /// <param name="permission">权限实体。</param>
    /// <param name="cancellationToken">取消标记。</param>
    /// <returns>异步任务。</returns>
    public Task UpdateAsync(Permission permission, CancellationToken cancellationToken = default)
    {
        // 1. 标记实体更新
        dbContext.Permissions.Update(permission);
        // 2. 返回完成任务
        return Task.CompletedTask;
    }

    /// <summary>
    /// 删除指定权限。
    /// </summary>
    /// <param name="permissionId">权限 ID。</param>
    /// <param name="cancellationToken">取消标记。</param>
    /// <returns>异步任务。</returns>
    public async Task DeleteAsync(long permissionId, CancellationToken cancellationToken = default)
    {
        // 1. 查询目标权限
        var entity = await dbContext.Permissions.FirstOrDefaultAsync(x => x.Id == permissionId, cancellationToken);
        if (entity != null)
        {
            // 2. 删除实体
            dbContext.Permissions.Remove(entity);
        }
    }

    /// <summary>
    /// 保存仓储变更。
    /// </summary>
    /// <param name="cancellationToken">取消标记。</param>
    /// <returns>保存任务。</returns>
    public Task SaveChangesAsync(CancellationToken cancellationToken = default)
        => dbContext.SaveChangesAsync(cancellationToken);
}
