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

namespace Workflow.Application.Form.FormDefinition.Commands;

public record PublishFormDefinitionCommand(Guid Id) : IRequest;

public class PublishFormDefinitionCommandHandler(WorkflowDbContext db)
    : IRequestHandler<PublishFormDefinitionCommand>
{
    public async Task Handle(PublishFormDefinitionCommand request, CancellationToken cancellationToken)
    {
        var entity = await db.FormDefinitions
            .FirstOrDefaultAsync(f => f.Id == request.Id, cancellationToken)
            ?? throw new NotFoundException($"表单 {request.Id} 不存在");

        if (entity.Status == FormStatus.Published)
        {
            throw new BusinessException("表单已发布，不能重复发布");
        }

        entity.Status = FormStatus.Published;
        await db.SaveChangesAsync(cancellationToken);
    }
}
