<?php

namespace App\Classes\Modules\Addresses\Services;


use App\Classes\General\Eloquent\AbstractUpdateRelationshipRecord;
use App\Classes\Modules\Addresses\DataTransferObjects\AddressObject;
use App\Models\Address;
use App\Models\Company;

class UpsertsAddress extends AbstractUpdateRelationshipRecord
{
    /**
     * Create or update the company's address.
     *
     * @param Company $company
     * @param AddressObject $object
     * @param int $id
     * @return \Illuminate\Database\Eloquent\Model
     * @throws \App\Classes\Exceptions\MalformedRequestException
     */
    public function execute(Company $company, AddressObject $object, int $id)
    {
        //Create new or update?
        $model = $company->addresses()->where('id', $id)->first() ?? new Address();

        $model->street_one = $object->getStreetOne();
        $model->street_two = $object->getStreetTwo();
        $model->country_id = $object->getCountryId();
        $model->state_id = $object->getStateId();
        $model->district_id = $object->getDistrictId();
        $model->postcode = $object->getPostCode();

        return $this->handler($company->addresses(), $model);
    }
}
