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

using MediatR;
using MerchantService.Domain.AggregatesModel.MerchantAggregate;
using MerchantService.Domain.Exceptions;

namespace MerchantService.API.Application.Commands.Merchants;

/// <summary>
/// EN: Handler for updating merchant information.
/// VI: Handler để cập nhật thông tin merchant.
/// </summary>
public class UpdateMerchantCommandHandler : IRequestHandler<UpdateMerchantCommand, bool>
{
    private readonly IMerchantRepository _merchantRepository;
    private readonly ILogger<UpdateMerchantCommandHandler> _logger;

    public UpdateMerchantCommandHandler(
        IMerchantRepository merchantRepository,
        ILogger<UpdateMerchantCommandHandler> logger)
    {
        _merchantRepository = merchantRepository;
        _logger = logger;
    }

    public async Task<bool> Handle(UpdateMerchantCommand request, CancellationToken cancellationToken)
    {
        // EN: Use user ID passed from the controller
        // VI: Dùng user ID được truyền từ controller
        var userId = request.UserId;

        // EN: Get merchant by user ID
        // VI: Lấy merchant theo user ID
        var merchant = await _merchantRepository.GetByUserIdAsync(userId, cancellationToken);
        if (merchant == null)
        {
            throw new DomainException("Merchant not found");
        }

        // EN: Update business name
        // VI: Cập nhật tên doanh nghiệp
        if (!string.IsNullOrWhiteSpace(request.BusinessName))
        {
            merchant.UpdateBusinessName(request.BusinessName);
        }

        // EN: Update business info
        // VI: Cập nhật thông tin doanh nghiệp
        if (!string.IsNullOrWhiteSpace(request.TaxId) || 
            !string.IsNullOrWhiteSpace(request.BusinessLicenseNumber) ||
            !string.IsNullOrWhiteSpace(request.CompanyRegistrationNumber))
        {
            merchant.UpdateBusinessInfo(new BusinessInfo
            {
                TaxId = request.TaxId ?? merchant.BusinessInfo.TaxId,
                BusinessLicenseNumber = request.BusinessLicenseNumber ?? merchant.BusinessInfo.BusinessLicenseNumber,
                CompanyRegistrationNumber = request.CompanyRegistrationNumber ?? merchant.BusinessInfo.CompanyRegistrationNumber,
                EstablishedDate = merchant.BusinessInfo.EstablishedDate
            });
        }

        // EN: Update settlement config if bank info provided
        // VI: Cập nhật cấu hình thanh toán nếu có thông tin ngân hàng
        if (!string.IsNullOrWhiteSpace(request.BankAccountNumber))
        {
            merchant.UpdateSettlementConfig(new SettlementConfig
            {
                BankAccount = new BankAccount
                {
                    BankCode = request.BankCode ?? merchant.SettlementConfig.BankAccount.BankCode,
                    BankName = request.BankName ?? merchant.SettlementConfig.BankAccount.BankName,
                    AccountNumber = request.BankAccountNumber,
                    AccountHolderName = request.BankAccountHolderName ?? merchant.SettlementConfig.BankAccount.AccountHolderName
                },
                CommissionRate = merchant.SettlementConfig.CommissionRate,
                SettlementCycleId = merchant.SettlementConfig.SettlementCycleId,
                AutoSettlement = merchant.SettlementConfig.AutoSettlement
            });
        }

        // EN: Save changes
        // VI: Lưu thay đổi
        _merchantRepository.Update(merchant);
        await _merchantRepository.UnitOfWork.SaveEntitiesAsync(cancellationToken);

        _logger.LogInformation("Merchant updated: {MerchantId}", merchant.Id);

        return true;
    }
}
