using MediatR;
using Microsoft.EntityFrameworkCore;
using Workflow.Application.Common;
using Workflow.Application.Features.WorkflowTasks.DTOs;
using Workflow.Domain.Enums;
using Workflow.Infrastructure.Persistence;

using TaskStatus = Workflow.Domain.Enums.TaskStatus;

namespace Workflow.Application.Features.WorkflowTasks.Queries;

public record GetPendingTasksQuery(
    Guid UserId,
    int PageIndex,
    int PageSize
) : IRequest<PagedResult<WorkflowTaskListItemDto>>;

public class GetPendingTasksQueryHandler(WorkflowDbContext db)
    : IRequestHandler<GetPendingTasksQuery, PagedResult<WorkflowTaskListItemDto>>
{
    public async Task<PagedResult<WorkflowTaskListItemDto>> Handle(GetPendingTasksQuery request, CancellationToken cancellationToken)
    {
        var query = db.WorkflowTasks
            .Where(t => t.AssigneeId == request.UserId && t.Status == TaskStatus.Pending);

        var total = await query.CountAsync(cancellationToken);
        var items = await query
            .OrderByDescending(t => t.CreatedAt)
            .Skip((request.PageIndex - 1) * request.PageSize)
            .Take(request.PageSize)
            .Select(t => new WorkflowTaskListItemDto(
                t.Id,
                t.InstanceId,
                t.TokenId,
                t.AssigneeId,
                t.Status,
                t.Title,
                t.CompletedAt
            ))
            .ToListAsync(cancellationToken);

        return new PagedResult<WorkflowTaskListItemDto>
        {
            Items = items,
            Total = total,
            PageIndex = request.PageIndex,
            PageSize = request.PageSize
        };
    }
}
