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

namespace Workflow.Application.Features.WorkflowDefinitions.Commands;

public record CreateWorkflowDefinitionCommand(
    string Name,
    string Code,
    string? Description
) : IRequest<WorkflowDefinitionDto>;

public class CreateWorkflowDefinitionCommandHandler(WorkflowDbContext db)
    : IRequestHandler<CreateWorkflowDefinitionCommand, WorkflowDefinitionDto>
{
    public async Task<WorkflowDefinitionDto> Handle(CreateWorkflowDefinitionCommand request, CancellationToken cancellationToken)
    {
        // Check for duplicate code
        var exists = await db.WorkflowDefinitions.AnyAsync(d => d.Code == request.Code, cancellationToken);
        if (exists)
        {
            throw new BusinessException($"Workflow definition with code '{request.Code}' already exists.");
        }

        var entity = new WorkflowDefinition
        {
            Id = Guid.NewGuid(),
            Name = request.Name,
            Code = request.Code,
            Description = request.Description,
            Status = DefinitionStatus.Draft,
            Version = 1,
            IsEnabled = true
        };

        db.WorkflowDefinitions.Add(entity);
        await db.SaveChangesAsync(cancellationToken);

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