using MediatR;
using Microsoft.EntityFrameworkCore;
using ColaFlow.Modules.ProjectManagement.Application.Common.Interfaces;
using ColaFlow.Modules.ProjectManagement.Domain.Repositories;
using ColaFlow.Modules.ProjectManagement.Domain.ValueObjects;
using ColaFlow.Modules.ProjectManagement.Domain.Exceptions;

namespace ColaFlow.Modules.ProjectManagement.Application.Commands.RemoveTaskFromSprint;

/// <summary>
/// Handler for RemoveTaskFromSprintCommand
/// </summary>
public sealed class RemoveTaskFromSprintCommandHandler(
    IApplicationDbContext context,
    IUnitOfWork unitOfWork)
    : IRequestHandler<RemoveTaskFromSprintCommand, Unit>
{
    private readonly IApplicationDbContext _context = context ?? throw new ArgumentNullException(nameof(context));
    private readonly IUnitOfWork _unitOfWork = unitOfWork ?? throw new ArgumentNullException(nameof(unitOfWork));

    public async Task<Unit> Handle(RemoveTaskFromSprintCommand request, CancellationToken cancellationToken)
    {
        // Get sprint with tracking
        var sprintId = SprintId.From(request.SprintId);
        var sprint = await _context.Sprints
            .FirstOrDefaultAsync(s => s.Id == sprintId, cancellationToken);

        if (sprint == null)
            throw new NotFoundException("Sprint", request.SprintId);

        // Remove task from sprint
        var taskId = TaskId.From(request.TaskId);
        sprint.RemoveTask(taskId);

        // Save changes
        await _unitOfWork.SaveChangesAsync(cancellationToken);

        return Unit.Value;
    }
}
