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;
using ColaFlow.Modules.ProjectManagement.Domain.Aggregates.ProjectAggregate;

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

/// <summary>
/// Handler for UpdateTaskCommand
/// </summary>
public sealed class UpdateTaskCommandHandler(
    IProjectRepository projectRepository,
    IUnitOfWork unitOfWork,
    ITenantContext tenantContext)
    : IRequestHandler<UpdateTaskCommand, TaskDto>
{
    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<TaskDto> Handle(UpdateTaskCommand request, CancellationToken cancellationToken)
    {
        // Get current tenant ID (Defense in Depth - Layer 2)
        var currentTenantId = _tenantContext.GetCurrentTenantId();

        // Get the project containing the task (Global Query Filter ensures tenant isolation)
        var taskId = TaskId.From(request.TaskId);
        var project = await _projectRepository.GetProjectWithTaskAsync(taskId, cancellationToken);

        if (project == null)
            throw new NotFoundException("Task", request.TaskId);

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

        // Find the task within the project aggregate
        WorkTask? task = null;
        foreach (var epic in project.Epics)
        {
            foreach (var story in epic.Stories)
            {
                task = story.Tasks.FirstOrDefault(t => t.Id.Value == request.TaskId);
                if (task != null)
                    break;
            }
            if (task != null)
                break;
        }

        if (task == null)
            throw new NotFoundException("Task", request.TaskId);

        // Update task details
        task.UpdateDetails(request.Title, request.Description);

        // Update priority if provided
        if (!string.IsNullOrWhiteSpace(request.Priority))
        {
            var priority = TaskPriority.FromDisplayName<TaskPriority>(request.Priority);
            task.UpdatePriority(priority);
        }

        // Update status if provided
        if (!string.IsNullOrWhiteSpace(request.Status))
        {
            var status = WorkItemStatus.FromDisplayName<WorkItemStatus>(request.Status);
            task.UpdateStatus(status);
        }

        // Update estimated hours if provided
        if (request.EstimatedHours.HasValue)
        {
            task.UpdateEstimate(request.EstimatedHours.Value);
        }

        // Update assignee if provided
        if (request.AssigneeId.HasValue)
        {
            var assigneeId = UserId.From(request.AssigneeId.Value);
            task.AssignTo(assigneeId);
        }

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

        // Map to DTO
        return new TaskDto
        {
            Id = task.Id.Value,
            Title = task.Title,
            Description = task.Description,
            StoryId = task.StoryId.Value,
            Status = task.Status.Name,
            Priority = task.Priority.Name,
            AssigneeId = task.AssigneeId?.Value,
            EstimatedHours = task.EstimatedHours,
            ActualHours = task.ActualHours,
            CreatedBy = task.CreatedBy.Value,
            CreatedAt = task.CreatedAt,
            UpdatedAt = task.UpdatedAt
        };
    }
}
