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

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

    public async Task<SprintDto?> Handle(GetSprintByIdQuery request, CancellationToken cancellationToken)
    {
        var sprintId = SprintId.From(request.SprintId);
        var sprint = await _projectRepository.GetSprintByIdReadOnlyAsync(sprintId, cancellationToken);

        if (sprint == null)
            return null;

        // Get project name
        var project = await _projectRepository.GetByIdAsync(sprint.ProjectId, cancellationToken);

        return new SprintDto
        {
            Id = sprint.Id.Value,
            ProjectId = sprint.ProjectId.Value,
            ProjectName = project?.Name ?? string.Empty,
            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
        };
    }
}
