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

namespace Workflow.Application.Form.FormDefinition.Commands;

public record CreateFormDefinitionCommand(
    string Name,
    string Code,
    string? Description,
    List<FormFieldDto> Fields
) : IRequest<FormDefinitionDto>;

public class CreateFormDefinitionCommandHandler(WorkflowDbContext db)
    : IRequestHandler<CreateFormDefinitionCommand, FormDefinitionDto>
{
    public async Task<FormDefinitionDto> Handle(CreateFormDefinitionCommand request, CancellationToken cancellationToken)
    {
        // 检查编码是否重复
        var exists = await db.FormDefinitions
            .AnyAsync(f => f.Code == request.Code, cancellationToken);
        if (exists)
        {
            throw new BusinessException($"表单编码 {request.Code} 已存在");
        }

        var entity = new Domain.Entities.FormDefinition
        {
            Id = Guid.NewGuid(),
            Name = request.Name,
            Code = request.Code,
            Description = request.Description,
            Version = 1,
            Status = FormStatus.Draft,
            SchemaJson = "{}",
        };

        foreach (var fieldDto in request.Fields)
        {
            entity.Fields.Add(new FormDefinitionField
            {
                Id = Guid.NewGuid(),
                FormDefinitionId = entity.Id,
                FieldKey = fieldDto.FieldKey,
                Label = fieldDto.Label,
                FieldType = fieldDto.FieldType,
                Required = fieldDto.Required,
                DefaultValue = fieldDto.DefaultValue,
                Config = fieldDto.Config,
                SortOrder = fieldDto.SortOrder,
            });
        }

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

        return new FormDefinitionDto
        {
            Id = entity.Id,
            Name = entity.Name,
            Code = entity.Code,
            Description = entity.Description,
            Version = entity.Version,
            Status = entity.Status,
        };
    }
}
