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

namespace Workflow.Application.Features.WorkflowTasks.Queries;

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

public class GetCcTasksQueryHandler(WorkflowDbContext db)
    : IRequestHandler<GetCcTasksQuery, PagedResult<WorkflowTaskListItemDto>>
{
    public async Task<PagedResult<WorkflowTaskListItemDto>> Handle(GetCcTasksQuery request, CancellationToken cancellationToken)
    {
        var query = db.WorkflowTasks
            .Where(t => t.AssigneeId == request.UserId && t.Type == TaskType.Cc);

        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
        };
    }
}
