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

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

    public async Task<List<EpicDto>> Handle(GetEpicsByProjectIdQuery request, CancellationToken cancellationToken)
    {
        // Use read-only method for query (AsNoTracking for better performance)
        var projectId = ProjectId.From(request.ProjectId);
        var epics = await _projectRepository.GetEpicsByProjectIdAsync(projectId, cancellationToken);

        return epics.Select(epic => new EpicDto
        {
            Id = epic.Id.Value,
            Name = epic.Name,
            Description = epic.Description,
            ProjectId = epic.ProjectId.Value,
            Status = epic.Status.Name,
            Priority = epic.Priority.Name,
            CreatedBy = epic.CreatedBy.Value,
            CreatedAt = epic.CreatedAt,
            UpdatedAt = epic.UpdatedAt,
            Stories = new List<StoryDto>() // Don't include stories in list view
        }).ToList();
    }
}
