#nullable enable
using Baya.Application.Contracts.Persistence;
using Baya.Application.Models.Common;
using Baya.Application.Models.PartnerCenters;
using Mediator;

namespace Baya.Application.Features.PartnerCenters.Commands.UpdatePartnerCenter;

internal sealed class UpdatePartnerCenterCommandHandler(IUnitOfWork unitOfWork)
    : IRequestHandler<UpdatePartnerCenterCommand, OperationResult<PartnerCenterDetailDto>>
{
    public async ValueTask<OperationResult<PartnerCenterDetailDto>> Handle(UpdatePartnerCenterCommand request, CancellationToken cancellationToken)
    {
        var center = await unitOfWork.PartnerCenterRepository.GetTrackedAsync(request.Id, cancellationToken);
        if (center is null)
            return OperationResult<PartnerCenterDetailDto>.NotFoundResult("Partner center not found.");

        center.Name = request.Name;
        center.LegalEntityType = request.LegalEntityType;
        center.MohEstablishmentPermitNo = request.MohEstablishmentPermitNo;
        center.TechnicalDirectorNurseUserId = request.TechnicalDirectorNurseUserId;
        center.TechnicalDirectorLicenseNo = request.TechnicalDirectorLicenseNo;
        center.EnamadCode = request.EnamadCode;
        center.SettlementIban = string.IsNullOrWhiteSpace(request.SettlementIban) ? null : request.SettlementIban;
        center.IsMerchantOfRecord = request.IsMerchantOfRecord;
        center.CommissionRate = request.CommissionRate;
        center.AdminUserId = request.AdminUserId;

        await unitOfWork.CommitAsync();

        var detail = await unitOfWork.PartnerCenterRepository.GetDetailAsync(center.Id, cancellationToken);
        return OperationResult<PartnerCenterDetailDto>.SuccessResult(detail!);
    }
}
