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.AddTaskToSprint;

/// <summary>
/// Handler for AddTaskToSprintCommand
/// </summary>
public sealed class AddTaskToSprintCommandHandler(
    IApplicationDbContext context,
    IUnitOfWork unitOfWork)
    : IRequestHandler<AddTaskToSprintCommand, 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(AddTaskToSprintCommand 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);

        // Verify task exists
        var taskId = TaskId.From(request.TaskId);
        var taskExists = await _context.Tasks
            .AnyAsync(t => t.Id == taskId, cancellationToken);

        if (!taskExists)
            throw new NotFoundException("Task", request.TaskId);

        // Add task to sprint
        sprint.AddTask(taskId);

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

        return Unit.Value;
    }
}
