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

namespace Workflow.Application.Features.WorkflowDefinitions.Queries;

public record GetWorkflowDefinitionListQuery(
    int PageIndex,
    int PageSize,
    DefinitionStatus? Status
) : IRequest<PagedResult<WorkflowDefinitionDto>>;

public class GetWorkflowDefinitionListQueryHandler(WorkflowDbContext db)
    : IRequestHandler<GetWorkflowDefinitionListQuery, PagedResult<WorkflowDefinitionDto>>
{
    public async Task<PagedResult<WorkflowDefinitionDto>> Handle(GetWorkflowDefinitionListQuery request, CancellationToken cancellationToken)
    {
        var query = db.WorkflowDefinitions.AsQueryable();

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

        var total = await query.CountAsync(cancellationToken);
        var items = await query
            .OrderByDescending(d => d.CreatedAt)
            .Skip((request.PageIndex - 1) * request.PageSize)
            .Take(request.PageSize)
            .Select(d => new WorkflowDefinitionDto(
                d.Id,
                d.Name,
                d.Code,
                d.Description,
                d.Status,
                d.Version,
                d.DefinitionJson,
                d.IsEnabled
            ))
            .ToListAsync(cancellationToken);

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