<?php

namespace App\Classes\Modules\Addresses\Processors;

use App\Classes\General\Interfaces\Addressable;
use App\Classes\Modules\Addresses\Services\CleansOldAddress;
use App\Classes\Modules\Addresses\Services\CreatesAddress;
use App\Classes\Modules\Addresses\Services\FetchesAddress;
use App\Models\OldAddress;
use App\Models\Order;
use Illuminate\Database\Eloquent\Model;

class CreateAddressFromOldAddressProcessor
{

    /** @var CleansOldAddress */
    private $cleansOldAddress;

    /** @var CreatesAddress */
    private $createsAddress;


    /**
     * CreateAddressFromOldAddressProcessor constructor.
     * @param CleansOldAddress $cleansOldAddress
     * @param CreatesAddress $createsAddress
     */
    public function __construct(CleansOldAddress $cleansOldAddress, CreatesAddress $createsAddress)
    {
        $this->cleansOldAddress = $cleansOldAddress;
        $this->createsAddress = $createsAddress;
    }


    /**
     * @param OldAddress $address
     * @param Addressable $addressable
     * @return Model|null
     * @throws \App\Classes\Exceptions\MalformedRequestException
     */
    public function execute(OldAddress $address, Addressable $addressable): ?Model {

        if(!$object = $this->cleansOldAddress->execute($address)){
            return null;
        }


        if(!$addressable instanceof Order && $address = $addressable->addresses()->where('street_one', $object->getStreetOne())->first()) {
            return $address;
        }

        return $this->createsAddress->execute($addressable, $object);

    }

}
