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

namespace Workflow.Application.Form.FormDefinition.Queries;

public record GetFormDefinitionByIdQuery(Guid Id) : IRequest<FormDefinitionDetailDto>;

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

        return new FormDefinitionDetailDto
        {
            Id = entity.Id,
            Name = entity.Name,
            Code = entity.Code,
            Description = entity.Description,
            Version = entity.Version,
            Status = entity.Status,
            Fields = entity.Fields
                .OrderBy(f => f.SortOrder)
                .Select(f => new FormDefinitionFieldDto
                {
                    Id = f.Id,
                    FieldKey = f.FieldKey,
                    Label = f.Label,
                    FieldType = f.FieldType,
                    Required = f.Required,
                    DefaultValue = f.DefaultValue,
                    Config = f.Config,
                    SortOrder = f.SortOrder,
                })
                .ToList(),
        };
    }
}
