<?php

namespace Velis\Dto\Validators;

use Attribute;
use InvalidArgumentException;

#[Attribute]
class Exists extends BaseValidator
{
    public function __construct(
        private readonly string $objectClass,
        private readonly bool $nullable = false,
    ) {
    }

    public function validate($value): bool
    {
        if ($this->nullable && is_null($value)) {
            return true;
        }

        if (!method_exists($this->objectClass, 'bufferedInstance')) {
            throw new InvalidArgumentException("The {$this->objectClass} must have bufferedInstance method");
        }

        return (bool) $this->objectClass::bufferedInstance($value);
    }

    public function getMessage(): string
    {
        return "Value of property does not exist";
    }
}
