using MediatR;
using Workflow.Domain.Enums;
using Workflow.Domain.Exceptions;
using Workflow.Infrastructure.Persistence;

namespace Workflow.Application.Features.WorkflowInstances.Commands;

public record SuspendWorkflowInstanceCommand(Guid InstanceId) : IRequest<Unit>;

public class SuspendWorkflowInstanceCommandHandler(WorkflowDbContext db)
    : IRequestHandler<SuspendWorkflowInstanceCommand, Unit>
{
    public async Task<Unit> Handle(SuspendWorkflowInstanceCommand request, CancellationToken cancellationToken)
    {
        var instance = await db.WorkflowInstances.FindAsync([request.InstanceId], cancellationToken)
            ?? throw new NotFoundException($"Workflow instance '{request.InstanceId}' not found.");

        instance.Status = InstanceStatus.Suspended;

        await db.SaveChangesAsync(cancellationToken);

        return Unit.Value;
    }
}
