<?php

declare(strict_types=1);

namespace App\Modules\Shared\Domain\ValueObject;

use DateTime;
use InvalidArgumentException;
use Stringable;

class TimeValueObject implements Stringable
{
    protected static $format = 'H:i:s';
    protected DateTime $value;

    public static function format()
    {
        return self::$format;
    }

    public function __construct(string $value)
    {
        $this->ensureIsValidDate($value);
        $this->value = DateTime::createFromFormat(self::$format, $value);
    }

    public function value(): string
    {
        return $this->value->format(self::$format);
    }

    public function __toString(): string
    {
        return $this->value();
    }

    private function ensureIsValidDate(string $date): void
    {
        $dt = DateTime::createFromFormat(self::$format, $date);
        if (!$dt || $dt->format(self::$format) !== $date) {
            throw new InvalidArgumentException(sprintf('%s does not allow the value %s.', static::class, $date));
        }
    }
}
