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

/// <summary>
/// Handler for UpdateEpicCommand
/// </summary>
public sealed class UpdateEpicCommandHandler(
    IProjectRepository projectRepository,
    IUnitOfWork unitOfWork,
    ITenantContext tenantContext)
    : IRequestHandler<UpdateEpicCommand, EpicDto>
{
    private readonly IProjectRepository _projectRepository = projectRepository ?? throw new ArgumentNullException(nameof(projectRepository));
    private readonly IUnitOfWork _unitOfWork = unitOfWork ?? throw new ArgumentNullException(nameof(unitOfWork));
    private readonly ITenantContext _tenantContext = tenantContext ?? throw new ArgumentNullException(nameof(tenantContext));

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

        // Get the project containing the epic (Global Query Filter ensures tenant isolation)
        var epicId = EpicId.From(request.EpicId);
        var project = await _projectRepository.GetProjectWithEpicAsync(epicId, cancellationToken);

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

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

        // Find the epic
        var epic = project.Epics.FirstOrDefault(e => e.Id == epicId);
        if (epic == null)
            throw new NotFoundException("Epic", request.EpicId);

        // Update epic through domain method
        epic.UpdateDetails(request.Name, request.Description);

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

        // Map to DTO
        return new EpicDto
        {
            Id = epic.Id.Value,
            Name = epic.Name,
            Description = epic.Description,
            ProjectId = epic.ProjectId.Value,
            Status = epic.Status.Name,
            Priority = epic.Priority.Name,
            CreatedBy = epic.CreatedBy.Value,
            CreatedAt = epic.CreatedAt,
            UpdatedAt = epic.UpdatedAt,
            Stories = epic.Stories.Select(s => new StoryDto
            {
                Id = s.Id.Value,
                Title = s.Title,
                Description = s.Description,
                EpicId = s.EpicId.Value,
                Status = s.Status.Name,
                Priority = s.Priority.Name,
                EstimatedHours = s.EstimatedHours,
                ActualHours = s.ActualHours,
                AssigneeId = s.AssigneeId?.Value,
                CreatedBy = s.CreatedBy.Value,
                CreatedAt = s.CreatedAt,
                UpdatedAt = s.UpdatedAt,
                Tasks = new List<TaskDto>()
            }).ToList()
        };
    }
}
