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

namespace Workflow.Application.Features.WorkflowTasks.Queries;

public record GetTaskByIdQuery(Guid Id) : IRequest<WorkflowTaskListItemDto>;

public class GetTaskByIdQueryHandler(WorkflowDbContext db)
    : IRequestHandler<GetTaskByIdQuery, WorkflowTaskListItemDto>
{
    public async Task<WorkflowTaskListItemDto> Handle(GetTaskByIdQuery request, CancellationToken cancellationToken)
    {
        var task = await db.WorkflowTasks.FindAsync([request.Id], cancellationToken)
            ?? throw new NotFoundException($"Task '{request.Id}' not found.");

        return new WorkflowTaskListItemDto(
            task.Id,
            task.InstanceId,
            task.TokenId,
            task.AssigneeId,
            task.Status,
            task.Title,
            task.CompletedAt
        );
    }
}
