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

namespace Workflow.Application.Features.WorkflowInstances.Queries;

public record GetWorkflowInstanceListQuery(
    int PageIndex,
    int PageSize,
    InstanceStatus? Status,
    Guid? InitiatorId
) : IRequest<PagedResult<WorkflowInstanceDto>>;

public class GetWorkflowInstanceListQueryHandler(WorkflowDbContext db)
    : IRequestHandler<GetWorkflowInstanceListQuery, PagedResult<WorkflowInstanceDto>>
{
    public async Task<PagedResult<WorkflowInstanceDto>> Handle(GetWorkflowInstanceListQuery request, CancellationToken cancellationToken)
    {
        var query = db.WorkflowInstances.AsQueryable();

        if (request.Status.HasValue)
        {
            query = query.Where(i => i.Status == request.Status.Value);
        }

        if (request.InitiatorId.HasValue)
        {
            query = query.Where(i => i.InitiatorId == request.InitiatorId.Value);
        }

        var total = await query.CountAsync(cancellationToken);
        var items = await query
            .OrderByDescending(i => i.StartedAt)
            .Skip((request.PageIndex - 1) * request.PageSize)
            .Take(request.PageSize)
            .Select(i => new WorkflowInstanceDto(
                i.Id,
                i.DefinitionId,
                i.Title,
                i.Status,
                i.InitiatorId,
                i.StartedAt,
                i.CompletedAt
            ))
            .ToListAsync(cancellationToken);

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