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

namespace Workflow.Application.Form.FormDefinition.Commands;

public record UpdateFormDefinitionCommand(
    Guid Id,
    string Name,
    string? Description,
    List<FormFieldDto> Fields
) : IRequest<FormDefinitionDto>;

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

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

        // 根据 FieldKey 匹配，处理字段的增删改
        var existingFields = entity.Fields.ToDictionary(f => f.FieldKey);
        var requestedKeys = request.Fields.Select(f => f.FieldKey).ToHashSet();

        // 删除不在请求中的字段
        var fieldsToRemove = entity.Fields
            .Where(f => !requestedKeys.Contains(f.FieldKey))
            .ToList();
        foreach (var field in fieldsToRemove)
        {
            entity.Fields.Remove(field);
            db.FormDefinitionFields.Remove(field);
        }

        // 更新已有字段或新增字段
        foreach (var fieldDto in request.Fields)
        {
            if (existingFields.TryGetValue(fieldDto.FieldKey, out var existingField))
            {
                // 更新已有字段属性
                existingField.Label = fieldDto.Label;
                existingField.FieldType = fieldDto.FieldType;
                existingField.Required = fieldDto.Required;
                existingField.DefaultValue = fieldDto.DefaultValue;
                existingField.Config = fieldDto.Config;
                existingField.SortOrder = fieldDto.SortOrder;
            }
            else
            {
                // 新增字段
                entity.Fields.Add(new Domain.Entities.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,
                });
            }
        }

        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,
        };
    }
}
