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

namespace TakeoutSaaS.Infrastructure.Identity.Persistence;

/// <summary>
/// EF 角色仓储。
/// </summary>
public sealed class EfRoleRepository(IdentityDbContext dbContext) : IRoleRepository
{
    /// <summary>
    /// 根据角色 ID 获取角色。
    /// </summary>
    /// <param name="roleId">角色 ID。</param>
    /// <param name="tenantId">租户 ID。</param>
    /// <param name="cancellationToken">取消标记。</param>
    /// <returns>角色实体或 null。</returns>
    public Task<Role?> FindByIdAsync(long roleId, long tenantId, CancellationToken cancellationToken = default)
        => dbContext.Roles
            .AsNoTracking()
            .FirstOrDefaultAsync(x => x.Id == roleId && x.TenantId == tenantId && x.DeletedAt == null, cancellationToken);

    /// <summary>
    /// 根据角色编码获取角色。
    /// </summary>
    /// <param name="code">角色编码。</param>
    /// <param name="tenantId">租户 ID。</param>
    /// <param name="cancellationToken">取消标记。</param>
    /// <returns>角色实体或 null。</returns>
    public Task<Role?> FindByCodeAsync(string code, long tenantId, CancellationToken cancellationToken = default)
        => dbContext.Roles
            .AsNoTracking()
            .FirstOrDefaultAsync(x => x.Code == code && x.TenantId == tenantId && x.DeletedAt == null, cancellationToken);

    /// <summary>
    /// 根据角色 ID 集合获取角色列表。
    /// </summary>
    /// <param name="tenantId">租户 ID。</param>
    /// <param name="roleIds">角色 ID 集合。</param>
    /// <param name="cancellationToken">取消标记。</param>
    /// <returns>角色列表。</returns>
    public async Task<IReadOnlyList<Role>> GetByIdsAsync(long tenantId, IEnumerable<long> roleIds, CancellationToken cancellationToken = default)
    {
        // 1. 查询角色列表
        var roles = await dbContext.Roles
            .AsNoTracking()
            .Where(x => x.TenantId == tenantId && roleIds.Contains(x.Id) && x.DeletedAt == null)
            .ToListAsync(cancellationToken);

        // 2. (空行后) 返回只读列表
        return roles;
    }

    /// <summary>
    /// 按关键字搜索角色。
    /// </summary>
    /// <param name="tenantId">租户 ID。</param>
    /// <param name="keyword">搜索关键字。</param>
    /// <param name="cancellationToken">取消标记。</param>
    /// <returns>角色列表。</returns>
    public async Task<IReadOnlyList<Role>> SearchAsync(long tenantId, string? keyword, CancellationToken cancellationToken = default)
    {
        // 1. 构建基础查询
        var query = dbContext.Roles
            .AsNoTracking()
            .Where(x => x.TenantId == tenantId && x.DeletedAt == null);
        if (!string.IsNullOrWhiteSpace(keyword))
        {
            // 2. 追加关键字过滤
            var normalized = keyword.Trim();
            query = query.Where(x => x.Name.Contains(normalized) || x.Code.Contains(normalized));
        }

        // 3. 返回列表
        var roles = await query.ToListAsync(cancellationToken);

        // 4. (空行后) 返回只读列表
        return roles;
    }

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

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

    /// <summary>
    /// 软删除角色。
    /// </summary>
    /// <param name="roleId">角色 ID。</param>
    /// <param name="tenantId">租户 ID。</param>
    /// <param name="cancellationToken">取消标记。</param>
    /// <returns>异步任务。</returns>
    public async Task DeleteAsync(long roleId, long tenantId, CancellationToken cancellationToken = default)
    {
        // 1. 查询目标角色
        var entity = await dbContext.Roles.FirstOrDefaultAsync(x => x.Id == roleId && x.TenantId == tenantId, cancellationToken);
        if (entity != null)
        {
            // 2. 标记删除时间
            entity.DeletedAt = DateTime.UtcNow;
            dbContext.Roles.Update(entity);
        }
    }

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