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

namespace Workflow.Application.Features.WorkflowDefinitions.Commands;

public record UpdateWorkflowDefinitionCommand(
    Guid Id,
    string Name,
    string? Description,
    string? DefinitionJson
) : IRequest<WorkflowDefinitionDto>;

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

        entity.Name = request.Name;
        entity.Description = request.Description;
        entity.DefinitionJson = request.DefinitionJson;

        await db.SaveChangesAsync(cancellationToken);

        return new WorkflowDefinitionDto(
            entity.Id,
            entity.Name,
            entity.Code,
            entity.Description,
            entity.Status,
            entity.Version,
            entity.DefinitionJson,
            entity.IsEnabled
        );
    }
}
