using MediatR;
using MktZaloService.Domain.AggregatesModel.CustomerAggregate;

namespace MktZaloService.API.Application.Queries.Customers;

/// <summary>
/// EN: Handler for GetCustomerQuery.
/// VI: Handler cho GetCustomerQuery.
/// </summary>
public class GetCustomerQueryHandler : 
    IRequestHandler<GetCustomerQuery, CustomerDto?>,
    IRequestHandler<GetCustomerByZaloIdQuery, CustomerDto?>
{
    private readonly ICustomerRepository _customerRepository;

    public GetCustomerQueryHandler(ICustomerRepository customerRepository)
    {
        _customerRepository = customerRepository;
    }

    public async Task<CustomerDto?> Handle(
        GetCustomerQuery request,
        CancellationToken cancellationToken)
    {
        var customer = await _customerRepository.GetByIdAsync(request.CustomerId, cancellationToken);
        return customer != null ? MapToDto(customer) : null;
    }

    public async Task<CustomerDto?> Handle(
        GetCustomerByZaloIdQuery request,
        CancellationToken cancellationToken)
    {
        var customer = await _customerRepository.FindByZaloUserIdAsync(request.ZaloUserId, cancellationToken);
        return customer != null ? MapToDto(customer) : null;
    }

    private static CustomerDto MapToDto(ZaloCustomer customer)
    {
        return new CustomerDto(
            customer.Id,
            customer.ZaloUserId,
            customer.Profile.DisplayName,
            customer.Profile.AvatarUrl,
            customer.Profile.PhoneNumber,
            customer.Profile.Email,
            customer.Segment.ToString(),
            customer.ConversationCount,
            customer.TotalMessageCount,
            customer.IsActive,
            customer.FirstInteractionAt,
            customer.LastInteractionAt,
            customer.Tags.Select(t => t.Name).ToList()
        );
    }
}
