<?php

namespace App\Casts;

use App\ValueObjects\PhoneNumber as PhoneNumberVO;
use Illuminate\Contracts\Database\Eloquent\CastsAttributes;
use Illuminate\Database\Eloquent\Model;

class PhoneNumber implements CastsAttributes {
    /**
     * Cast the database value to a PhoneNumber value object.
     */
    public function get(Model $model, string $key, mixed $value, array $attributes): ?PhoneNumberVO {
        if (blank($value)) {
            return null;
        }


        return PhoneNumberVO::tryFrom($value);
    }

    /**
     * Cast the given value to an E.164 string for storage.
     */
    public function set(Model $model, string $key, mixed $value, array $attributes): ?string {
        if (blank($value)) {
            return null;
        }

        if ($value instanceof PhoneNumberVO) {
            return $value->toE164();
        }

        $phone = PhoneNumberVO::tryFrom($value);

        return $phone?->toE164();
    }
}
