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 GetHistoryTasksQuery(
    Guid UserId,
    int PageIndex,
    int PageSize
) : IRequest<PagedResult<WorkflowTaskListItemDto>>;

public class GetHistoryTasksQueryHandler(WorkflowDbContext db)
    : IRequestHandler<GetHistoryTasksQuery, PagedResult<WorkflowTaskListItemDto>>
{
    public async Task<PagedResult<WorkflowTaskListItemDto>> Handle(GetHistoryTasksQuery request, CancellationToken cancellationToken)
    {
        var completedStatuses = new[] { TaskStatus.Approved, TaskStatus.Rejected };

        var query = db.WorkflowTasks
            .Where(t => t.AssigneeId == request.UserId && completedStatuses.Contains(t.Status));

        var total = await query.CountAsync(cancellationToken);
        var items = await query
            .OrderByDescending(t => t.CompletedAt)
            .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
        };
    }
}
