<?php

namespace App\Classes\Modules\Vouchers\Processors\Voucherify;

use App\Classes\Modules\Vouchers\Services\CreatesVoucherEntityMapping;
use App\Classes\Modules\Vouchers\Services\Voucherify\CreatesVoucherifyCustomer;
use App\Classes\Modules\Vouchers\DataTransferObjects\CreateVoucherifyCustomerObject;
use App\Classes\Modules\Vouchers\DataTransferObjects\VoucherEntityObject;
use App\Classes\ValueObjects\Constants\VoucherifyEntityType;
use App\Models\User;
use Illuminate\Support\Facades\Log;

class NewCustomerToVoucherifyProcessor
{
    /** @var CreatesVoucherEntityMapping */
    private $createsVoucherEntityMapping;

    /** @var CreatesVoucherifyCustomer */
    private $createsVoucherifyCustomer;

    /**
     * NewCustomerToVoucherifyProcessor constructor.
     * @param CreatesVoucherEntityMapping $createsVoucherEntityMapping
     * @param CreatesVoucherifyCustomer $createsVoucherifyCustomer
    */
    public function __construct(CreatesVoucherEntityMapping $createsVoucherEntityMapping, CreatesVoucherifyCustomer $createsVoucherifyCustomer)
    {
        $this->createsVoucherEntityMapping = $createsVoucherEntityMapping;
        $this->createsVoucherifyCustomer = $createsVoucherifyCustomer;
    }


    /**
     * @param int $companyId
     * @param User $user
     * @param bool $isNew
     * @return void
     * @throws \App\Classes\Exceptions\MalformedRequestException
     */
    public function execute(int $companyId, User $user, bool $isNew)
    {
        try
        {
            $createVoucherifyCustomerObject = new CreateVoucherifyCustomerObject($companyId, $user, $isNew);
            $result = $this->createsVoucherifyCustomer->execute($createVoucherifyCustomerObject);

            if($result && isset($result->id)){
                $voucherEntityObject = new VoucherEntityObject($result->id, VoucherifyEntityType::CUSTOMER);
                $this->createsVoucherEntityMapping->execute($createVoucherifyCustomerObject->getUser(), $voucherEntityObject);
            }
        } catch (\Exception $e) {
            Log::error($e);
        }
    }
}
