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

namespace ColaFlow.Modules.ProjectManagement.Application.Commands.AssignStory;

/// <summary>
/// Handler for AssignStoryCommand
/// </summary>
public sealed class AssignStoryCommandHandler(
    IProjectRepository projectRepository,
    IUnitOfWork unitOfWork)
    : IRequestHandler<AssignStoryCommand, StoryDto>
{
    private readonly IProjectRepository _projectRepository = projectRepository ?? throw new ArgumentNullException(nameof(projectRepository));
    private readonly IUnitOfWork _unitOfWork = unitOfWork ?? throw new ArgumentNullException(nameof(unitOfWork));

    public async Task<StoryDto> Handle(AssignStoryCommand request, CancellationToken cancellationToken)
    {
        // Get the project with story (Global Query Filter ensures tenant isolation)
        var storyId = StoryId.From(request.StoryId);
        var project = await _projectRepository.GetProjectWithStoryAsync(storyId, cancellationToken);

        if (project == null)
            throw new NotFoundException("Story", request.StoryId);

        // Find the story
        var story = project.Epics
            .SelectMany(e => e.Stories)
            .FirstOrDefault(s => s.Id.Value == request.StoryId);

        if (story == null)
            throw new NotFoundException("Story", request.StoryId);

        // Assign to user
        var assigneeId = UserId.From(request.AssigneeId);
        story.AssignTo(assigneeId);

        // Save changes
        _projectRepository.Update(project);
        await _unitOfWork.SaveChangesAsync(cancellationToken);

        // Map to DTO
        return new StoryDto
        {
            Id = story.Id.Value,
            Title = story.Title,
            Description = story.Description,
            EpicId = story.EpicId.Value,
            Status = story.Status.Name,
            Priority = story.Priority.Name,
            AssigneeId = story.AssigneeId?.Value,
            EstimatedHours = story.EstimatedHours,
            ActualHours = story.ActualHours,
            CreatedBy = story.CreatedBy.Value,
            CreatedAt = story.CreatedAt,
            UpdatedAt = story.UpdatedAt,
            Tasks = story.Tasks.Select(t => new TaskDto
            {
                Id = t.Id.Value,
                Title = t.Title,
                Description = t.Description,
                StoryId = t.StoryId.Value,
                Status = t.Status.Name,
                Priority = t.Priority.Name,
                AssigneeId = t.AssigneeId?.Value,
                EstimatedHours = t.EstimatedHours,
                ActualHours = t.ActualHours,
                CreatedBy = t.CreatedBy.Value,
                CreatedAt = t.CreatedAt,
                UpdatedAt = t.UpdatedAt
            }).ToList()
        };
    }
}
