using MediatR;
using ColaFlow.Modules.ProjectManagement.Domain.Repositories;
using ColaFlow.Modules.ProjectManagement.Domain.ValueObjects;
using ColaFlow.Modules.ProjectManagement.Domain.Exceptions;

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

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

    public async Task<Unit> Handle(ArchiveProjectCommand request, CancellationToken cancellationToken)
    {
        // Get project (will be filtered by tenant automatically)
        var project = await _projectRepository.GetByIdAsync(ProjectId.From(request.ProjectId), cancellationToken);
        if (project == null)
        {
            throw new NotFoundException($"Project with ID '{request.ProjectId}' not found");
        }

        // Archive project
        project.Archive();

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

        return Unit.Value;
    }
}
