using MediatR;
using FacebookService.Domain.AggregatesModel.CustomerAggregate;

namespace FacebookService.API.Application.Commands;

/// <summary>
/// EN: Handler for UpdateCustomerCommand.
/// VI: Handler cho UpdateCustomerCommand.
/// </summary>
public class UpdateCustomerCommandHandler : IRequestHandler<UpdateCustomerCommand, UpdateCustomerCommandResult>
{
    private readonly ICustomerRepository _customerRepository;
    private readonly ILogger<UpdateCustomerCommandHandler> _logger;

    public UpdateCustomerCommandHandler(
        ICustomerRepository customerRepository,
        ILogger<UpdateCustomerCommandHandler> logger)
    {
        _customerRepository = customerRepository ?? throw new ArgumentNullException(nameof(customerRepository));
        _logger = logger ?? throw new ArgumentNullException(nameof(logger));
    }

    public async Task<UpdateCustomerCommandResult> Handle(
        UpdateCustomerCommand request,
        CancellationToken cancellationToken)
    {
        _logger.LogInformation(
            "Processing UpdateCustomerCommand for CustomerId: {CustomerId}",
            request.CustomerId);

        var customer = await _customerRepository.GetByIdAsync(request.CustomerId, cancellationToken);

        if (customer is null)
        {
            _logger.LogWarning("Customer not found: {CustomerId}", request.CustomerId);
            return new UpdateCustomerCommandResult(Success: false, request.CustomerId);
        }

        // EN: Update tags if provided / VI: Cập nhật tags nếu được cung cấp
        if (request.Tags is not null)
        {
            // EN: Clear existing tags and add new ones / VI: Xóa tags hiện có và thêm mới
            var currentTags = customer.Tags.ToList();
            foreach (var tag in currentTags)
            {
                customer.RemoveTag(tag);
            }
            foreach (var tag in request.Tags)
            {
                customer.AddTag(tag);
            }
        }

        // EN: Update custom fields if provided / VI: Cập nhật custom fields nếu được cung cấp
        if (request.CustomFields is not null)
        {
            foreach (var (key, value) in request.CustomFields)
            {
                customer.SetCustomField(key, value);
            }
        }

        _customerRepository.Update(customer);
        await _customerRepository.UnitOfWork.SaveEntitiesAsync(cancellationToken);

        _logger.LogInformation(
            "Customer updated successfully: {CustomerId}",
            customer.Id);

        return new UpdateCustomerCommandResult(Success: true, customer.Id);
    }
}
