<?php

declare(strict_types=1);

namespace App\Casts;

use App\ValueObjects\Amount;
use Illuminate\Contracts\Database\Eloquent\CastsAttributes;
use Illuminate\Database\Eloquent\Model;

class AmountCast implements CastsAttributes
{
    public function get(Model $model, string $key, mixed $value, array $attributes): ?Amount
    {
        if ($value === null) {
            return null;
        }

        return new Amount((float) $value, 'Euro');
    }

    public function set(Model $model, string $key, mixed $value, array $attributes): ?float
    {
        if ($value === null) {
            return null;
        }

        if ($value instanceof Amount) {
            return $value->getAmount();
        }

        return (float) $value;
    }
}
