<?php

namespace App\Classes\Modules\FreightForwarder\Services;

use App\Classes\Modules\ControllerLogic\Exceptions\InternalServerErrorException;
use App\Classes\Modules\FreightForwarder\DataTransferObjects\CustomerRelationObject;
use App\Classes\ValueObjects\Constants\HttpStatus;
use App\Models\CustomerRelation;
use Illuminate\Http\JsonResponse;

class UpdatesCustomerRelation
{
    /** @var  CustomerRelation */
    private $repository;

    /**
     * UpdatesCustomerRelation constructor.
     * @param CustomerRelation $repository
     */
    public function __construct(CustomerRelation $repository)
    {
        $this->repository = $repository;
    }

    public function execute(CustomerRelationObject $customerRelationObject){

        try{

            $this->repository->updateOrCreate(
                [
                    'forwarder_id' => $customerRelationObject->getForwarderId(),
                    'company_id' => $customerRelationObject->getCompanyId(),
                ],
                [
                    'customer_rate' => $customerRelationObject->getCustomerRate(),
                    'wave' => $customerRelationObject->isWave(),
                ]);

            return new JsonResponse([],HttpStatus::OK);

        }catch(\Exception $exception){
            throw new InternalServerErrorException("Failed to update Customer Relation because {$exception->getMessage()}");
        }
    }

}