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.Queries.GetStoriesByEpicId;

/// <summary>
/// Handler for GetStoriesByEpicIdQuery
/// </summary>
public sealed class GetStoriesByEpicIdQueryHandler(
    IProjectRepository projectRepository,
    ITenantContext tenantContext)
    : IRequestHandler<GetStoriesByEpicIdQuery, List<StoryDto>>
{
    private readonly IProjectRepository _projectRepository = projectRepository ?? throw new ArgumentNullException(nameof(projectRepository));
    private readonly ITenantContext _tenantContext = tenantContext ?? throw new ArgumentNullException(nameof(tenantContext));

    public async Task<List<StoryDto>> Handle(GetStoriesByEpicIdQuery request, CancellationToken cancellationToken)
    {
        // Get current tenant ID (Defense in Depth - Layer 2)
        var currentTenantId = _tenantContext.GetCurrentTenantId();

        // CRITICAL SECURITY: Verify Epic belongs to current tenant before querying stories
        var epicId = EpicId.From(request.EpicId);
        var epic = await _projectRepository.GetEpicByIdReadOnlyAsync(epicId, cancellationToken);

        if (epic == null)
            throw new NotFoundException("Epic", request.EpicId);

        // Explicit TenantId validation (Defense in Depth)
        if (epic.TenantId.Value != currentTenantId)
            throw new NotFoundException("Epic", request.EpicId);

        // Now fetch stories (already filtered by EF Core, but we verified epic ownership)
        var stories = await _projectRepository.GetStoriesByEpicIdAsync(epicId, cancellationToken);

        // Map stories to DTOs
        return stories.Select(story => 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()
        }).ToList();
    }
}
