<?php

namespace App\Rules;

use Illuminate\Contracts\Validation\Rule;
use Illuminate\Support\Facades\Redis;

class ExistsInRedis implements Rule
{
    protected $key;
    protected $field;
    protected $checkType;

    /**
     * Create a new rule instance.
     *
     * @param string $key The Redis key to check
     * @param string|null $field Optional field for hash/set operations
     * @param string $checkType Type of check: 'key', 'hash', 'set', 'list'
     */
    public function __construct($key, $field = null, $checkType = 'key')
    {
        $this->key = $key;
        $this->field = $field;
        $this->checkType = $checkType;
    }

    /**
     * Determine if the validation rule passes.
     *
     * @param  string  $attribute
     * @param  mixed  $value
     * @return bool
     */
    public function passes($attribute, $value)
    {
        try {
            switch ($this->checkType) {
                case 'key':
                    return Redis::exists(str_replace('{value}', $value, $this->key)) > 0;
                case 'hash':
                    return Redis::hexists($this->key, $value);
                case 'set':
                    return Redis::sismember($this->key, $value);
                case 'list':
                    $list = Redis::lrange($this->key, 0, -1);
                    return in_array($value, $list);
                case 'value':
                    return Redis::get($this->key) === $value;                    
                default:
                    return false;
            }
        } catch (\Exception $ex) {
            return false;
        }
    }

    /**
     * Get the validation error message.
     *
     * @return string
     */
    public function message()
    {
        return 'The :attribute does not exist in the required Redis store.';
    }
}