using MediatR;
using ColaFlow.Modules.ProjectManagement.Application.DTOs;
using ColaFlow.Modules.ProjectManagement.Domain.Repositories;
using ColaFlow.Modules.ProjectManagement.Domain.ValueObjects;
using ColaFlow.Modules.ProjectManagement.Domain.Exceptions;

namespace ColaFlow.Modules.ProjectManagement.Application.Queries.GetTasksByStoryId;

/// <summary>
/// Handler for GetTasksByStoryIdQuery
/// </summary>
public sealed class GetTasksByStoryIdQueryHandler(IProjectRepository projectRepository)
    : IRequestHandler<GetTasksByStoryIdQuery, List<TaskDto>>
{
    private readonly IProjectRepository _projectRepository = projectRepository ?? throw new ArgumentNullException(nameof(projectRepository));

    public async Task<List<TaskDto>> Handle(GetTasksByStoryIdQuery request, CancellationToken cancellationToken)
    {
        // Get the project containing the story
        var storyId = StoryId.From(request.StoryId);
        var project = await _projectRepository.GetProjectWithStoryAsync(storyId, cancellationToken);

        if (project == null)
            throw new NotFoundException("Story", request.StoryId);

        // Find the story within the project aggregate
        var story = project.Epics
            .SelectMany(e => e.Stories)
            .FirstOrDefault(s => s.Id.Value == request.StoryId);

        if (story == null)
            throw new NotFoundException("Story", request.StoryId);

        // Map tasks to DTOs
        return story.Tasks.Select(task => new TaskDto
        {
            Id = task.Id.Value,
            Title = task.Title,
            Description = task.Description,
            StoryId = task.StoryId.Value,
            Status = task.Status.Name,
            Priority = task.Priority.Name,
            AssigneeId = task.AssigneeId?.Value,
            EstimatedHours = task.EstimatedHours,
            ActualHours = task.ActualHours,
            CreatedBy = task.CreatedBy.Value,
            CreatedAt = task.CreatedAt,
            UpdatedAt = task.UpdatedAt
        }).ToList();
    }
}
