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 TransferTaskCommand(
    Guid TaskId,
    Guid FromUserId,
    Guid ToUserId
) : IRequest<Unit>;

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

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

        // Mark original task as transferred
        task.Status = TaskStatus.Transferred;
        task.CompletedAt = DateTime.UtcNow;

        await db.SaveChangesAsync(cancellationToken);

        return Unit.Value;
    }
}
