<?php

namespace Myvetshop\Module\Clinique\Import\Kalivet\Sync;

use Myvetshop\Module\Clinique\Import\ImportFile\DispatchedCustomerData;
use Myvetshop\Module\Clinique\Import\Kalivet\Model\CustomerModel;
use Myvetshop\Module\Clinique\Import\Kalivet\Model\RewardModel;
use Myvetshop\Module\Clinique\Import\Sync\Syncer;
use Myvetshop\Module\Clinique\Import\Sync\SyncStatistics;

class KalivetDataSyncer
{
    protected Syncer\AddressesSyncer $addressesSyncer;
    protected Syncer\CustomerSyncer $customerSyncer;
    protected Syncer\OrdersSyncer $ordersSyncer;

    protected Syncer\RewardSyncer $rewardSyncer;

    public function __construct(
        Syncer\AddressesSyncer $addressesSyncer,
        Syncer\CustomerSyncer $customerSyncer,
        Syncer\OrdersSyncer $ordersSyncer,
        Syncer\RewardSyncer $rewardSyncer
    ) {
        $this->addressesSyncer = $addressesSyncer;
        $this->customerSyncer = $customerSyncer;
        $this->ordersSyncer = $ordersSyncer;
        $this->rewardSyncer = $rewardSyncer;
    }

    /**
     * @param array<string, \Clinique> $clinicMap
     */
    public function sync(array $clinicMap, DispatchedCustomerData $data, SyncStatistics $syncStatistics): void
    {
        $customerModel = $data->getCustomer(CustomerModel::class);
        \assert($customerModel instanceof CustomerModel);

        $clinique = $clinicMap[$customerModel->idVetoAlcyon ?? ''] ?? null;

        if (!$clinique) {
            throw new \Exception(\sprintf('Clinic not found : %s', $customerModel->idVetoAlcyon));
        }

        $customer = $this->customerSyncer->sync($syncStatistics, $clinique, $customerModel);
        $addressMap = $this->addressesSyncer->sync($syncStatistics, $customer, $data->getAdresses());
        $ordersMaps = $this->ordersSyncer->sync(
            $syncStatistics,
            $customer,
            $clinique,
            $addressMap,
            $data->getOrders(),
            $data->getOrderDetails(),
            $data->getOrderDetailTaxes(),
        );

        $reward = $data->getReward(RewardModel::class);
        if ($reward) {
            $this->rewardSyncer->sync($customer, $reward);
        }
    }
}
