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

namespace Workflow.Application.Features.WorkflowDefinitions.Commands;

public record PublishWorkflowDefinitionCommand(Guid Id) : IRequest<Unit>;

public class PublishWorkflowDefinitionCommandHandler(WorkflowDbContext db)
    : IRequestHandler<PublishWorkflowDefinitionCommand, Unit>
{
    public async Task<Unit> Handle(PublishWorkflowDefinitionCommand request, CancellationToken cancellationToken)
    {
        var entity = await db.WorkflowDefinitions.FindAsync([request.Id], cancellationToken)
            ?? throw new NotFoundException($"Workflow definition '{request.Id}' not found.");

        if (entity.Status != DefinitionStatus.Draft)
        {
            throw new BusinessException("Only draft workflow definitions can be published.");
        }

        entity.Status = DefinitionStatus.Published;
        entity.Version++;

        await db.SaveChangesAsync(cancellationToken);

        return Unit.Value;
    }
}
