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

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

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

        // Use read-only method for query (AsNoTracking for better performance)
        var storyId = StoryId.From(request.StoryId);
        var story = await _projectRepository.GetStoryByIdReadOnlyAsync(storyId, cancellationToken);

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

        // CRITICAL SECURITY: Explicit TenantId validation (Defense in Depth)
        if (story.TenantId.Value != currentTenantId)
            throw new NotFoundException("Story", request.StoryId);

        // 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()
        };
    }
}
