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

namespace Workflow.Application.Form.FormData.Queries;

public record GetFormDataByInstanceQuery(Guid InstanceId) : IRequest<FormDataDto?>;

public class GetFormDataByInstanceQueryHandler(WorkflowDbContext db)
    : IRequestHandler<GetFormDataByInstanceQuery, FormDataDto?>
{
    public async Task<FormDataDto?> Handle(GetFormDataByInstanceQuery request, CancellationToken cancellationToken)
    {
        var entity = await db.FormData
            .FirstOrDefaultAsync(f => f.InstanceId == request.InstanceId, cancellationToken);

        if (entity is null)
        {
            return null;
        }

        return new FormDataDto
        {
            Id = entity.Id,
            FormDefinitionId = entity.FormDefinitionId,
            InstanceId = entity.InstanceId,
            DataJson = entity.DataJson,
        };
    }
}
