<?php

declare(strict_types=1);

namespace Flowaxy\Domain\User\ValueObjects;

use InvalidArgumentException;

use function hash_equals;
use function password_hash;
use function password_verify;
use function strlen;
use const PASSWORD_DEFAULT;

// Value Object для пароля
class Password
{
    private const MIN_LENGTH = 8;

    public function __construct(
        private readonly string $value,
        private readonly bool $isHashed = false,
    ) {
        if (!$isHashed && strlen($value) < self::MIN_LENGTH) {
            throw new InvalidArgumentException("Password must be at least " . self::MIN_LENGTH . " characters long");
        }
    }

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

    public function isHashed(): bool
    {
        return $this->isHashed;
    }

    public function hash(): string
    {
        if ($this->isHashed) {
            return $this->value;
        }

        return password_hash($this->value, PASSWORD_DEFAULT);
    }

    public function verify(string $hash): bool
    {
        if ($this->isHashed) {
            return hash_equals($this->value, $hash);
        }

        return password_verify($this->value, $hash);
    }
}
