<?php

declare(strict_types=1);

namespace Myvetshop\Module\Clinique\Persister;

class AnimalPersister
{
    private \Customer $customer;

    private string $token;

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

    public function save(\Animal $animal, ?string $token): bool
    {
        if (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, ?string $token): bool
    {
        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;
    }
}
