<?php

namespace App\Rules;

use App\Services\Auth\PasswordHistoryService;
use Closure;
use Illuminate\Contracts\Validation\ValidationRule;

/**
 * PRC-135 — validation rule: candidate password must NOT match any of the
 * user's last N stored hashes.
 *
 * Usage:
 *   'new_password' => ['required', 'string', 'min:8', new PasswordNotInHistory('admin', $admin->id)]
 */
class PasswordNotInHistory implements ValidationRule
{
    public function __construct(
        private string $userType,
        private int $userId,
    ) {}

    public function validate(string $attribute, mixed $value, Closure $fail): void
    {
        if (! is_string($value) || $value === '') {
            return;
        }

        $svc = app(PasswordHistoryService::class);
        if (! $svc->isAllowed($this->userType, $this->userId, $value)) {
            $fail(__('admin/auth.password_in_history'));
        }
    }
}
