<?php

namespace App\Rules;

use Closure;
use Illuminate\Contracts\Validation\ValidationRule;
use Illuminate\Support\Str;

class PasswordRule implements ValidationRule
{

    protected $minLength;
    protected $requireUppercase;
    protected $requireNumeric;
    protected $requireSpecialCharacter;

    public function __construct(
        int $minLength = 8,
        bool $requireUppercase = true,
        bool $requireNumeric = true,
        bool $requireSpecialCharacter = true
    ) {
        $this->minLength = $minLength;
        $this->requireUppercase = $requireUppercase;
        $this->requireNumeric = $requireNumeric;
        $this->requireSpecialCharacter = $requireSpecialCharacter;
    }

    /**
     * Run the validation rule.
     *
     * @param  \Closure(string, ?string=): \Illuminate\Translation\PotentiallyTranslatedString  $fail
     */
    public function validate(string $attribute, mixed $value, Closure $fail): void
    {
        //
    }

    public function passes($attribute, $value)
    {
        $passes = true;

        if (strlen($value) < $this->minLength) {
            $passes = false;
        }

        if ($this->requireUppercase && !preg_match('/[A-Z]/', $value)) {
            $passes = false;
        }

        if ($this->requireNumeric && !preg_match('/[0-9]/', $value)) {
            $passes = false;
        }

        if ($this->requireSpecialCharacter && !preg_match('/[\W_]/', $value)) {
            $passes = false;
        }

        return $passes;
    }

    public function message()
    {
        return 'La contraseña debe contener al menos '.$this->minLength.' caracteres'.
               ($this->requireUppercase ? ', una mayúscula' : '').
               ($this->requireNumeric ? ', un número' : '').
               ($this->requireSpecialCharacter ? ' y un carácter especial' : '');
    }
}
