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

namespace Workflow.Application.Features.WorkflowInstances.Queries;

public record GetWorkflowInstanceByIdQuery(Guid Id) : IRequest<WorkflowInstanceDetailDto>;

public class GetWorkflowInstanceByIdQueryHandler(WorkflowDbContext db)
    : IRequestHandler<GetWorkflowInstanceByIdQuery, WorkflowInstanceDetailDto>
{
    public async Task<WorkflowInstanceDetailDto> Handle(GetWorkflowInstanceByIdQuery request, CancellationToken cancellationToken)
    {
        var entity = await db.WorkflowInstances
            .Include(i => i.Tokens)
            .Include(i => i.Tasks)
            .FirstOrDefaultAsync(i => i.Id == request.Id, cancellationToken)
            ?? throw new NotFoundException($"Workflow instance '{request.Id}' not found.");

        return new WorkflowInstanceDetailDto(
            entity.Id,
            entity.DefinitionId,
            entity.Title,
            entity.Status,
            entity.InitiatorId,
            entity.StartedAt,
            entity.CompletedAt,
            entity.Tokens.Select(t => new WorkflowTokenDto(
                t.Id,
                t.NodeId,
                t.Status,
                t.ArrivedAt,
                t.CompletedAt
            )).ToList(),
            entity.Tasks.Select(t => new WorkflowTaskDto(
                t.Id,
                t.InstanceId,
                t.TokenId,
                t.AssigneeId,
                t.Status,
                t.CompletedAt
            )).ToList()
        );
    }
}
