using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using Knot.Contracts.Auth.Abstractions;
using Knot.Modules.Auth.Infrastructure.Persistence;
using Microsoft.EntityFrameworkCore;

namespace Knot.Modules.Auth.Infrastructure.Persistence;

public sealed class UserQueryService : IUserQueryService
{
    private readonly AuthDbContext _context;

    public UserQueryService(AuthDbContext context)
    {
        _context = context;
    }

    public async Task<List<UserInfo>> GetAllUsersAsync(CancellationToken cancellationToken)
    {
        var users = await _context.Users.AsNoTracking().ToListAsync(cancellationToken);
        return users.Select(u => new UserInfo(u.Id, u.Avatar, u.Username, u.DisplayName, u.CreatedAt, u.PhoneNumber, u.Email)).ToList();
    }

    public async Task<List<UserInfo>> SearchUsersAsync(string query, CancellationToken cancellationToken)
    {
        var users = await _context.Users
            .AsNoTracking()
            .Where(u => u.Username != null && u.Username.Contains(query) ||
                        u.DisplayName != null && u.DisplayName.Contains(query) ||
                        u.Email != null && u.Email.Contains(query) ||
                        u.PhoneNumber != null && u.PhoneNumber.Contains(query))
            .Take(50)
            .ToListAsync(cancellationToken);
        return users.Select(u => new UserInfo(u.Id, u.Avatar, u.Username, u.DisplayName, u.CreatedAt, u.PhoneNumber, u.Email)).ToList();
    }
}
