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

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

/// <summary>Persists a new partner center (inactive). <see cref="PartnerCenter.SettlementIban"/> is set in
/// plaintext on the entity and encrypted by the EF converter on save — it is never returned in plaintext (the
/// detail read masks it).</summary>
internal sealed class CreatePartnerCenterCommandHandler(IUnitOfWork unitOfWork)
    : IRequestHandler<CreatePartnerCenterCommand, OperationResult<PartnerCenterDetailDto>>
{
    public async ValueTask<OperationResult<PartnerCenterDetailDto>> Handle(CreatePartnerCenterCommand request, CancellationToken cancellationToken)
    {
        var center = new PartnerCenter
        {
            Name = request.Name,
            LegalEntityType = request.LegalEntityType,
            MohEstablishmentPermitNo = request.MohEstablishmentPermitNo,
            TechnicalDirectorNurseUserId = request.TechnicalDirectorNurseUserId,
            TechnicalDirectorLicenseNo = request.TechnicalDirectorLicenseNo,
            EnamadCode = request.EnamadCode,
            SettlementIban = string.IsNullOrWhiteSpace(request.SettlementIban) ? null : request.SettlementIban,
            IsMerchantOfRecord = request.IsMerchantOfRecord,
            CommissionRate = request.CommissionRate,
            AdminUserId = request.AdminUserId
        };

        await unitOfWork.PartnerCenterRepository.AddAsync(center, cancellationToken);
        await unitOfWork.CommitAsync();

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