using MediatR;
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 ApproveTaskCommand(
    Guid TaskId,
    Guid UserId,
    string? Comment
) : IRequest<Unit>;

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

        if (task.AssigneeId != request.UserId)
        {
            throw new UnauthorizedException("Only the assignee can approve this task.");
        }

        task.Status = TaskStatus.Approved;
        task.Comment = request.Comment;
        task.CompletedAt = DateTime.UtcNow;

        await db.SaveChangesAsync(cancellationToken);

        return Unit.Value;
    }
}
