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

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

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

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

        return projects.Select(MapToDto).ToList();
    }

    private static ProjectDto MapToDto(Project project)
    {
        return new ProjectDto
        {
            Id = project.Id.Value,
            Name = project.Name,
            Description = project.Description,
            Key = project.Key.Value,
            Status = project.Status.Name,
            OwnerId = project.OwnerId.Value,
            CreatedAt = project.CreatedAt,
            UpdatedAt = project.UpdatedAt,
            // Don't load Epics for list view (performance)
            Epics = new List<EpicDto>()
        };
    }
}
