using MediatR;
using Workflow.Domain.Entities;
using Workflow.Domain.Enums;
using Workflow.Domain.Exceptions;
using Workflow.Infrastructure.Persistence;

using TaskStatus = Workflow.Domain.Enums.TaskStatus;

namespace Workflow.Application.Features.WorkflowTasks.Commands;

public record DelegateTaskCommand(
    Guid TaskId,
    Guid FromUserId,
    Guid ToUserId
) : IRequest<Unit>;

public class DelegateTaskCommandHandler(WorkflowDbContext db)
    : IRequestHandler<DelegateTaskCommand, Unit>
{
    public async Task<Unit> Handle(DelegateTaskCommand request, CancellationToken cancellationToken)
    {
        var task = await db.WorkflowTasks.FindAsync([request.TaskId], cancellationToken)
            ?? throw new NotFoundException($"Task '{request.TaskId}' not found.");

        // Create a new delegated task for the target user
        var newTask = new WorkflowTask
        {
            Id = Guid.NewGuid(),
            InstanceId = task.InstanceId,
            TokenId = task.TokenId,
            AssigneeId = request.ToUserId,
            DelegatedFromId = request.FromUserId,
            Status = TaskStatus.Pending,
            Title = task.Title,
            NodeId = task.NodeId
        };
        db.WorkflowTasks.Add(newTask);

        // Mark original task as delegated
        task.Status = TaskStatus.Delegated;

        await db.SaveChangesAsync(cancellationToken);

        return Unit.Value;
    }
}
