<?php

namespace App\Casts;

use App\ValueObjects\DOB as DOBValueObject;
use Illuminate\Contracts\Database\Eloquent\CastsAttributes;
use Illuminate\Database\Eloquent\Model;

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

        return new DOBValueObject($value);
    }

    public function set(Model $model, string $key, mixed $value, array $attributes): array {
        if (empty($value)) {
            return [$key => null];
        }

        $dob = $value instanceof \DateTimeInterface
            ? DOBValueObject::instance($value)
            : new DOBValueObject($value);

        return [$key => $dob->toDateString()];
    }
}
