using MediatR;
using Microsoft.EntityFrameworkCore;
using Workflow.Application.Form.DTOs;
using Workflow.Domain.Enums;
using Workflow.Infrastructure.Persistence;

namespace Workflow.Application.Form.FormDefinition.Queries;

public record GetFormDefinitionListQuery(
    int PageIndex,
    int PageSize,
    FormStatus? Status
) : IRequest<PagedResult<FormDefinitionDto>>;

public class GetFormDefinitionListQueryHandler(WorkflowDbContext db)
    : IRequestHandler<GetFormDefinitionListQuery, PagedResult<FormDefinitionDto>>
{
    public async Task<PagedResult<FormDefinitionDto>> Handle(GetFormDefinitionListQuery request, CancellationToken cancellationToken)
    {
        var query = db.FormDefinitions.AsQueryable();

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

        var totalCount = await query.CountAsync(cancellationToken);

        var items = await query
            .OrderByDescending(f => f.CreatedAt)
            .Skip((request.PageIndex - 1) * request.PageSize)
            .Take(request.PageSize)
            .Select(f => new FormDefinitionDto
            {
                Id = f.Id,
                Name = f.Name,
                Code = f.Code,
                Description = f.Description,
                Version = f.Version,
                Status = f.Status,
            })
            .ToListAsync(cancellationToken);

        return new PagedResult<FormDefinitionDto>
        {
            Items = items,
            TotalCount = totalCount,
            PageIndex = request.PageIndex,
            PageSize = request.PageSize,
        };
    }
}
