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

public class GetOverdueTasksQueryHandler(WorkflowDbContext db)
    : IRequestHandler<GetOverdueTasksQuery, PagedResult<WorkflowTaskListItemDto>>
{
    public async Task<PagedResult<WorkflowTaskListItemDto>> Handle(GetOverdueTasksQuery request, CancellationToken cancellationToken)
    {
        var query = db.WorkflowTasks
            .Where(t => t.Status == TaskStatus.Pending && t.DueAt != null && t.DueAt < DateTime.UtcNow);

        if (request.UserId.HasValue)
        {
            query = query.Where(t => t.AssigneeId == request.UserId.Value);
        }

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