<?php

declare(strict_types=1);

namespace apexl\Io\modules\validation\PhpValidatorRules;

use apexl\Vault\Vault;
use BlakvGhost\PHPValidator\Contracts\Rule;
use function apexl\Io\container;

final readonly class Unique implements Rule
{
    private string $table;
    private mixed $field;

    public function __construct(array $parameters)
    {
        [$this->table, $this->field] = $parameters;
    }

    public function passes(string $field, mixed $value, array $data): bool
    {
        if (!class_exists(Vault::class)) {
            return true;
        }

        return container()->get(Vault::class)->select($this->table)
                ->fields($this->field)
                ->where($this->field, $value)
                ->limit(1)
                ->execute()
                ->fetch() === false;
    }

    public function message(): string
    {
        return ':field already exists.';
    }
}