using Microsoft.EntityFrameworkCore;
using Modules.User.Application.Models;
using Modules.User.Application.Models.Access;
using Modules.User.Application.Repositories;
using Modules.User.Database.Database;

namespace Modules.User.Database.Queries;

public sealed class PermissionQueries(UserDbContext context) : IPermissionQueries
{
    public async Task<PagedData<PermissionShort>> GetPermissionsAsync(PermissionListFilter filter, CancellationToken cancellationToken = default)
    {
        var query = context.Permissions
            .AsNoTracking()
            .AsQueryable();

        var ids = filter.Ids.ToList();
        if (filter.Ids.Any())
            query = query.Where(r => ids.Contains(r.Id));

        if (!string.IsNullOrWhiteSpace(filter.NamesStartWith))
            query = query.Where(r => r.Name.StartsWith(filter.NamesStartWith));

        if (filter.CreatedAtFrom.HasValue)
            query = query.Where(r => r.CreationDate >= filter.CreatedAtFrom.Value.UtcDateTime);

        if (filter.CreatedAtTo.HasValue)
            query = query.Where(r => r.CreationDate <= filter.CreatedAtTo.Value.UtcDateTime);
        
        var count = await query.CountAsync(cancellationToken);
        // var take = ids.Count > 0 ? ids.Count :;
        var take = filter?.ItemsOnPage > 0 ? filter.ItemsOnPage : 10;
        var pagesCount = (int)Math.Ceiling((decimal)count / take);
        var page = filter?.Page ?? 1;
        if (page < 1) page = 1;
        if (page > pagesCount) page = pagesCount > 0 ? pagesCount : 1;
        var skip = (page - 1) * take;

        var items = await query
            .OrderBy(r => r.Name)
            .Skip(skip)
            .Take(take)
            .Select(p => new PermissionShort
            {
                Id = p.Id,
                Name = p.Name,
                Description = p.Description,
            })
            .ToListAsync(cancellationToken);

        return new PagedData<PermissionShort>
        {
            Page = page,
            ItemsOnPage = take,
            ItemsCount = count,
            PagesCount = pagesCount,
            Items = items
        };
    }

    public async Task<Permission?> GetDetailByIdAsync(int permissionId, CancellationToken cancellationToken = default)
    {
        return await context.Permissions
            .AsNoTracking()
            .Where(p => p.Id == permissionId)
            .Select(p => new Permission
                {
                    Id = p.Id,
                    Name = p.Name,
                    Code = p.Code,
                    Description = p.Description,
                    CreatedAt = p.CreationDate
            })
            .FirstOrDefaultAsync(cancellationToken);
    }
}
