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

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

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

    public async Task<List<TaskDto>> Handle(GetTasksByAssigneeQuery request, CancellationToken cancellationToken)
    {
        // Use read-only method for query (AsNoTracking for better performance)
        var allProjects = await _projectRepository.GetAllProjectsReadOnlyAsync(cancellationToken);

        // Get all tasks assigned to the user across all projects
        var userTasks = allProjects
            .SelectMany(project => project.Epics)
            .SelectMany(epic => epic.Stories)
            .SelectMany(story => story.Tasks)
            .Where(task => task.AssigneeId != null && task.AssigneeId.Value == request.AssigneeId)
            .ToList();

        // Map to DTOs
        return userTasks.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();
    }
}
