<?php

namespace Myvetshop\Module\Clinique\Persister;

use Animal;
use Customer;

class AnimalPersister
{
    private $customer;

    private $token;

    public function __construct(Customer $customer, string $token)
    {
        $this->customer = $customer;
        $this->token = $token;
    }

    public function save(Animal $animal, ?string $token): bool
    {
        if (is_null($token) || empty($token) || !$this->authorizeChange($animal, $token)) {
            return false;
        }

        $animal->id_customer = $this->customer->id;

        return $animal->save();
    }

    public function delete(Animal $animal): bool
    {
        return $animal->delete();
    }

    public function getToken(): string
    {
        return $this->token;
    }

    private function authorizeChange(Animal $animal, $token)
    {
        if ($animal->id_customer && (int) $animal->id_customer !== (int) $this->customer->id) {
            // Can't touch anybody else's address
            return false;
        }

        if ($token !== $this->token) {
            // XSS?
            return false;
        }

        return true;
    }
}
