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

using BookingService.API.Application.DTOs;
using BookingService.Domain.AggregatesModel.ResourceAggregate;
using BookingService.Infrastructure.Repositories;
using MediatR;

namespace BookingService.API.Application.Commands;

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

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

    public async Task<ResourceDto> Handle(CreateResourceCommand request, CancellationToken cancellationToken)
    {
        _logger.LogInformation("Creating resource {Name} for shop {ShopId}", request.Name, request.ShopId);

        var resource = new Resource(request.ShopId, request.Name, request.ResourceType, request.Capacity);
        
        _resourceRepository.Add(resource);
        await _resourceRepository.UnitOfWork.SaveEntitiesAsync(cancellationToken);

        _logger.LogInformation("Created 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
        };
    }
}
