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

namespace TakeoutSaaS.Infrastructure.Identity.Persistence;

/// <summary>
/// EF Core 后台用户仓储实现。
/// </summary>
public sealed class EfIdentityUserRepository(IdentityDbContext dbContext) : IIdentityUserRepository
{
    /// <summary>
    /// 根据租户与账号获取后台用户。
    /// </summary>
    /// <param name="tenantId">租户 ID。</param>
    /// <param name="account">账号。</param>
    /// <param name="cancellationToken">取消标记。</param>
    /// <returns>后台用户或 null。</returns>
    public Task<IdentityUser?> FindByAccountAsync(long tenantId, string account, CancellationToken cancellationToken = default)
    {
        // 1. 标准化账号
        var normalized = account.Trim();

        // 2. 查询用户（强制租户隔离）
        return dbContext.IdentityUsers
            .AsNoTracking()
            .FirstOrDefaultAsync(x => x.TenantId == tenantId && x.Account == normalized, cancellationToken);
    }

    /// <summary>
    /// 判断账号是否存在。
    /// </summary>
    /// <param name="account">账号。</param>
    /// <param name="cancellationToken">取消标记。</param>
    /// <returns>存在返回 true。</returns>
    public Task<bool> ExistsByAccountAsync(string account, CancellationToken cancellationToken = default)
    {
        // 1. 标准化账号
        var normalized = account.Trim();
        // 2. 查询是否存在
        return dbContext.IdentityUsers.AnyAsync(x => x.Account == normalized, cancellationToken);
    }

    /// <summary>
    /// 判断账号是否存在（租户内，可排除指定用户）。
    /// </summary>
    /// <param name="tenantId">租户 ID。</param>
    /// <param name="account">账号。</param>
    /// <param name="excludeUserId">排除的用户 ID。</param>
    /// <param name="cancellationToken">取消标记。</param>
    /// <returns>存在返回 true。</returns>
    public async Task<bool> ExistsByAccountAsync(long tenantId, string account, long? excludeUserId = null, CancellationToken cancellationToken = default)
    {
        // 1. 标准化账号
        var normalized = account.Trim();

        // 2. 构建查询（包含已删除数据，但不放开租户过滤）
        using var disableSoftDeleteScope = dbContext.DisableSoftDeleteFilter();
        var query = dbContext.IdentityUsers.AsNoTracking()
            .Where(x => x.TenantId == tenantId && x.Account == normalized);

        if (excludeUserId.HasValue)
        {
            query = query.Where(x => x.Id != excludeUserId.Value);
        }

        // 3. 返回是否存在
        return await query.AnyAsync(cancellationToken);
    }

    /// <summary>
    /// 判断手机号是否存在（租户内，可排除指定用户）。
    /// </summary>
    /// <param name="tenantId">租户 ID。</param>
    /// <param name="phone">手机号。</param>
    /// <param name="excludeUserId">排除的用户 ID。</param>
    /// <param name="cancellationToken">取消标记。</param>
    /// <returns>存在返回 true。</returns>
    public async Task<bool> ExistsByPhoneAsync(long tenantId, string phone, long? excludeUserId = null, CancellationToken cancellationToken = default)
    {
        // 1. 标准化手机号
        var normalized = phone.Trim();

        // 2. 构建查询（包含已删除数据，但不放开租户过滤）
        using var disableSoftDeleteScope = dbContext.DisableSoftDeleteFilter();
        var query = dbContext.IdentityUsers.AsNoTracking()
            .Where(x => x.TenantId == tenantId && x.Phone == normalized);

        if (excludeUserId.HasValue)
        {
            query = query.Where(x => x.Id != excludeUserId.Value);
        }

        // 3. 返回是否存在
        return await query.AnyAsync(cancellationToken);
    }

    /// <summary>
    /// 判断邮箱是否存在（租户内，可排除指定用户）。
    /// </summary>
    /// <param name="tenantId">租户 ID。</param>
    /// <param name="email">邮箱。</param>
    /// <param name="excludeUserId">排除的用户 ID。</param>
    /// <param name="cancellationToken">取消标记。</param>
    /// <returns>存在返回 true。</returns>
    public async Task<bool> ExistsByEmailAsync(long tenantId, string email, long? excludeUserId = null, CancellationToken cancellationToken = default)
    {
        // 1. 标准化邮箱
        var normalized = email.Trim();

        // 2. 构建查询（包含已删除数据，但不放开租户过滤）
        using var disableSoftDeleteScope = dbContext.DisableSoftDeleteFilter();
        var query = dbContext.IdentityUsers.AsNoTracking()
            .Where(x => x.TenantId == tenantId && x.Email == normalized);

        if (excludeUserId.HasValue)
        {
            query = query.Where(x => x.Id != excludeUserId.Value);
        }

        // 3. 返回是否存在
        return await query.AnyAsync(cancellationToken);
    }

    /// <summary>
    /// 根据 ID 获取后台用户。
    /// </summary>
    /// <param name="userId">用户 ID。</param>
    /// <param name="cancellationToken">取消标记。</param>
    /// <returns>后台用户或 null。</returns>
    public Task<IdentityUser?> FindByIdAsync(long userId, CancellationToken cancellationToken = default)
        => dbContext.IdentityUsers.AsNoTracking().FirstOrDefaultAsync(x => x.Id == userId, cancellationToken);

    /// <summary>
    /// 根据 ID 获取后台用户（用于更新，返回可跟踪实体）。
    /// </summary>
    /// <param name="userId">用户 ID。</param>
    /// <param name="cancellationToken">取消标记。</param>
    /// <returns>后台用户或 null。</returns>
    public Task<IdentityUser?> GetForUpdateAsync(long userId, CancellationToken cancellationToken = default)
        => dbContext.IdentityUsers.FirstOrDefaultAsync(x => x.Id == userId, cancellationToken);

    /// <summary>
    /// 根据 ID 获取后台用户（用于更新，包含已删除数据）。
    /// </summary>
    /// <param name="tenantId">租户 ID。</param>
    /// <param name="userId">用户 ID。</param>
    /// <param name="cancellationToken">取消标记。</param>
    /// <returns>后台用户或 null。</returns>
    public async Task<IdentityUser?> GetForUpdateIncludingDeletedAsync(
        long tenantId,
        long userId,
        CancellationToken cancellationToken = default)
    {
        // 1. 构建查询（包含已删除数据，但强制租户隔离）
        using var disableSoftDeleteScope = dbContext.DisableSoftDeleteFilter();
        return await dbContext.IdentityUsers
            .Where(x => x.TenantId == tenantId)
            .FirstOrDefaultAsync(x => x.Id == userId, cancellationToken);
    }

    /// <summary>
    /// 按租户与关键字搜索后台用户（只读）。
    /// </summary>
    /// <param name="tenantId">租户 ID。</param>
    /// <param name="keyword">关键字（账号/名称）。</param>
    /// <param name="cancellationToken">取消标记。</param>
    /// <returns>后台用户列表。</returns>
    public async Task<IReadOnlyList<IdentityUser>> SearchAsync(long tenantId, string? keyword, CancellationToken cancellationToken = default)
    {
        // 1. 构建基础查询
        var query = dbContext.IdentityUsers
            .AsNoTracking()
            .Where(x => x.TenantId == tenantId);

        // 2. 关键字过滤
        if (!string.IsNullOrWhiteSpace(keyword))
        {
            var normalized = keyword.Trim();
            query = query.Where(x => x.Account.Contains(normalized) || x.DisplayName.Contains(normalized));
        }

        // 3. 返回列表
        return await query.ToListAsync(cancellationToken);
    }

    /// <summary>
    /// 分页查询后台用户列表。
    /// </summary>
    /// <param name="filter">查询过滤条件。</param>
    /// <param name="cancellationToken">取消标记。</param>
    /// <returns>分页结果。</returns>
    public async Task<(IReadOnlyList<IdentityUser> Items, int Total)> SearchPagedAsync(
        IdentityUserSearchFilter filter,
        CancellationToken cancellationToken = default)
    {
        if (!filter.TenantId.HasValue || filter.TenantId.Value <= 0)
        {
            throw new InvalidOperationException("TenantId 不能为空且必须大于 0");
        }

        var tenantId = filter.TenantId.Value;

        using var disableSoftDeleteScope = filter.IncludeDeleted ? dbContext.DisableSoftDeleteFilter() : null;

        // 1. 构建基础查询
        var query = dbContext.IdentityUsers.AsNoTracking();

        // 2. 租户过滤（强制）
        query = query.Where(x => x.TenantId == tenantId);

        // 3. 关键字筛选
        if (!string.IsNullOrWhiteSpace(filter.Keyword))
        {
            var normalized = filter.Keyword.Trim();
            var likeValue = $"%{normalized}%";
            query = query.Where(x =>
                EF.Functions.ILike(x.Account, likeValue)
                || EF.Functions.ILike(x.DisplayName, likeValue)
                || (x.Phone != null && EF.Functions.ILike(x.Phone, likeValue))
                || (x.Email != null && EF.Functions.ILike(x.Email, likeValue)));
        }

        // 4. 状态过滤
        if (filter.Status.HasValue)
        {
            query = query.Where(x => x.Status == filter.Status.Value);
        }

        // 5. 角色过滤
        if (filter.RoleId.HasValue)
        {
            var roleId = filter.RoleId.Value;
            var userRoles = dbContext.UserRoles.AsNoTracking();

            userRoles = userRoles.Where(x => x.TenantId == tenantId);

            query = query.Where(user => userRoles.Any(role => role.UserId == user.Id && role.RoleId == roleId));
        }

        // 6. 时间范围过滤
        if (filter.CreatedAtFrom.HasValue)
        {
            query = query.Where(x => x.CreatedAt >= filter.CreatedAtFrom.Value);
        }

        if (filter.CreatedAtTo.HasValue)
        {
            query = query.Where(x => x.CreatedAt <= filter.CreatedAtTo.Value);
        }

        if (filter.LastLoginFrom.HasValue)
        {
            query = query.Where(x => x.LastLoginAt >= filter.LastLoginFrom.Value);
        }

        if (filter.LastLoginTo.HasValue)
        {
            query = query.Where(x => x.LastLoginAt <= filter.LastLoginTo.Value);
        }

        // 7. 排序
        var sorted = filter.SortBy?.ToLowerInvariant() switch
        {
            "account" => filter.SortDescending
                ? query.OrderByDescending(x => x.Account)
                : query.OrderBy(x => x.Account),
            "displayname" => filter.SortDescending
                ? query.OrderByDescending(x => x.DisplayName)
                : query.OrderBy(x => x.DisplayName),
            "status" => filter.SortDescending
                ? query.OrderByDescending(x => x.Status)
                : query.OrderBy(x => x.Status),
            "lastloginat" => filter.SortDescending
                ? query.OrderByDescending(x => x.LastLoginAt)
                : query.OrderBy(x => x.LastLoginAt),
            _ => filter.SortDescending
                ? query.OrderByDescending(x => x.CreatedAt)
                : query.OrderBy(x => x.CreatedAt)
        };

        // 8. 分页
        var page = filter.Page <= 0 ? 1 : filter.Page;
        var pageSize = filter.PageSize <= 0 ? 20 : filter.PageSize;
        var total = await sorted.CountAsync(cancellationToken);
        var items = await sorted
            .Skip((page - 1) * pageSize)
            .Take(pageSize)
            .ToListAsync(cancellationToken);

        return (items, total);
    }

    /// <summary>
    /// 根据 ID 集合批量获取后台用户（只读）。
    /// </summary>
    /// <param name="tenantId">租户 ID。</param>
    /// <param name="userIds">用户 ID 集合。</param>
    /// <param name="cancellationToken">取消标记。</param>
    /// <returns>后台用户列表。</returns>
    public async Task<IReadOnlyList<IdentityUser>> GetByIdsAsync(long tenantId, IEnumerable<long> userIds, CancellationToken cancellationToken = default)
    {
        return await dbContext.IdentityUsers.AsNoTracking()
            .Where(x => x.TenantId == tenantId && userIds.Contains(x.Id))
            .ToListAsync(cancellationToken);
    }

    /// <summary>
    /// 批量获取后台用户（可用于更新，支持包含已删除数据）。
    /// </summary>
    /// <param name="tenantId">租户 ID。</param>
    /// <param name="userIds">用户 ID 集合。</param>
    /// <param name="includeDeleted">是否包含已删除数据。</param>
    /// <param name="cancellationToken">取消标记。</param>
    /// <returns>后台用户列表。</returns>
    public async Task<IReadOnlyList<IdentityUser>> GetForUpdateByIdsAsync(
        long tenantId,
        IEnumerable<long> userIds,
        bool includeDeleted,
        CancellationToken cancellationToken = default)
    {
        // 1. 构建基础查询
        var ids = userIds.Distinct().ToArray();
        if (ids.Length == 0)
        {
            return Array.Empty<IdentityUser>();
        }

        var query = dbContext.IdentityUsers.Where(x => ids.Contains(x.Id));
        using var disableSoftDeleteScope = includeDeleted ? dbContext.DisableSoftDeleteFilter() : null;

        query = query.Where(x => x.TenantId == tenantId);

        // 2. 返回列表
        return await query.ToListAsync(cancellationToken);
    }

    /// <summary>
    /// 新增后台用户。
    /// </summary>
    /// <param name="user">后台用户实体。</param>
    /// <param name="cancellationToken">取消标记。</param>
    /// <returns>异步任务。</returns>
    public Task AddAsync(IdentityUser user, CancellationToken cancellationToken = default)
    {
        // 1. 添加实体
        dbContext.IdentityUsers.Add(user);
        // 2. 返回完成任务
        return Task.CompletedTask;
    }

    /// <summary>
    /// 删除后台用户（软删除）。
    /// </summary>
    /// <param name="user">后台用户实体。</param>
    /// <param name="cancellationToken">取消标记。</param>
    /// <returns>异步任务。</returns>
    public Task RemoveAsync(IdentityUser user, CancellationToken cancellationToken = default)
    {
        // 1. 标记删除
        dbContext.IdentityUsers.Remove(user);
        // 2. 返回完成任务
        return Task.CompletedTask;
    }

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