// EN: Handler for UpdateResourceCommand.
// VI: Handler cho UpdateResourceCommand.

using BookingService.API.Application.DTOs;
using BookingService.Domain.Exceptions;
using BookingService.Infrastructure.Repositories;
using MediatR;

namespace BookingService.API.Application.Commands;

public class UpdateResourceCommandHandler : IRequestHandler<UpdateResourceCommand, ResourceDto>
{
    private readonly IResourceRepository _resourceRepository;
    private readonly ILogger<UpdateResourceCommandHandler> _logger;

    public UpdateResourceCommandHandler(
        IResourceRepository resourceRepository,
        ILogger<UpdateResourceCommandHandler> logger)
    {
        _resourceRepository = resourceRepository ?? throw new ArgumentNullException(nameof(resourceRepository));
        _logger = logger ?? throw new ArgumentNullException(nameof(logger));
    }

    public async Task<ResourceDto> Handle(UpdateResourceCommand request, CancellationToken cancellationToken)
    {
        _logger.LogInformation("Updating resource {ResourceId}", request.ResourceId);

        var resource = await _resourceRepository.GetByIdAsync(request.ResourceId, cancellationToken);
        if (resource == null)
        {
            throw new DomainException($"Resource {request.ResourceId} not found");
        }

        // EN: Update via domain methods
        // VI: Cập nhật qua domain methods
        if (request.IsActive)
            resource.Activate();
        else
            resource.Deactivate();

        _resourceRepository.Update(resource);
        await _resourceRepository.UnitOfWork.SaveEntitiesAsync(cancellationToken);

        _logger.LogInformation("Updated resource {ResourceId}", resource.Id);

        return new ResourceDto
        {
            Id = resource.Id,
            ShopId = resource.ShopId,
            Name = resource.Name,
            ResourceType = resource.ResourceType,
            Capacity = resource.Capacity,
            IsActive = resource.IsActive,
            CreatedAt = resource.CreatedAt
        };
    }
}
