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

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

/// <summary>
/// Handler for GetSprintsByProjectIdQuery
/// </summary>
public sealed class GetSprintsByProjectIdQueryHandler(IProjectRepository projectRepository)
    : IRequestHandler<GetSprintsByProjectIdQuery, IReadOnlyList<SprintDto>>
{
    private readonly IProjectRepository _projectRepository = projectRepository ?? throw new ArgumentNullException(nameof(projectRepository));

    public async Task<IReadOnlyList<SprintDto>> Handle(GetSprintsByProjectIdQuery request, CancellationToken cancellationToken)
    {
        var projectId = ProjectId.From(request.ProjectId);
        var sprints = await _projectRepository.GetSprintsByProjectIdAsync(projectId, cancellationToken);

        // Get project name
        var project = await _projectRepository.GetByIdAsync(projectId, cancellationToken);
        var projectName = project?.Name ?? string.Empty;

        return sprints.Select(sprint => new SprintDto
        {
            Id = sprint.Id.Value,
            ProjectId = sprint.ProjectId.Value,
            ProjectName = projectName,
            Name = sprint.Name,
            Goal = sprint.Goal,
            StartDate = sprint.StartDate,
            EndDate = sprint.EndDate,
            Status = sprint.Status.Name,
            TotalTasks = sprint.TaskIds.Count,
            CompletedTasks = 0, // TODO: Calculate from tasks
            TotalStoryPoints = 0, // TODO: Calculate from tasks
            RemainingStoryPoints = 0, // TODO: Calculate from tasks
            TaskIds = sprint.TaskIds.Select(t => t.Value).ToList(),
            CreatedAt = sprint.CreatedAt,
            CreatedBy = sprint.CreatedBy.Value,
            UpdatedAt = sprint.UpdatedAt
        }).ToList();
    }
}
