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

namespace Workflow.Application.Features.WorkflowDefinitions.Queries;

public record GetWorkflowDefinitionByIdQuery(Guid Id) : IRequest<WorkflowDefinitionDetailDto>;

public class GetWorkflowDefinitionByIdQueryHandler(WorkflowDbContext db)
    : IRequestHandler<GetWorkflowDefinitionByIdQuery, WorkflowDefinitionDetailDto>
{
    public async Task<WorkflowDefinitionDetailDto> Handle(GetWorkflowDefinitionByIdQuery request, CancellationToken cancellationToken)
    {
        var entity = await db.WorkflowDefinitions
            .Include(d => d.Nodes)
            .Include(d => d.Edges)
            .FirstOrDefaultAsync(d => d.Id == request.Id, cancellationToken)
            ?? throw new NotFoundException($"Workflow definition '{request.Id}' not found.");

        return new WorkflowDefinitionDetailDto(
            entity.Id,
            entity.Name,
            entity.Code,
            entity.Description,
            entity.Status,
            entity.Version,
            entity.DefinitionJson,
            entity.IsEnabled,
            entity.Nodes.Select(n => new WorkflowNodeDto(
                n.Id,
                n.NodeType,
                n.Name,
                n.PositionX,
                n.PositionY
            )).ToList(),
            entity.Edges.Select(e => new WorkflowEdgeDto(
                e.Id,
                e.SourceNodeId,
                e.TargetNodeId,
                e.Label
            )).ToList()
        );
    }
}
