import type { Redis } from 'ioredis';
import type { StorageAdapter } from './adapter';

/**
 * Redis存储适配器实现
 * 使用Redis作为通用key-value存储
 */
export class RedisStorageAdapter implements StorageAdapter {
    private redis: Redis;
    private keyPrefix: string;

    constructor(redis: Redis, keyPrefix = 'oidc:') {
        this.redis = redis;
        this.keyPrefix = keyPrefix;
    }

    private getKey(key: string): string {
        return `${this.keyPrefix}${key}`;
    }

    async set(key: string, value: any, ttl?: number): Promise<void> {
        const redisKey = this.getKey(key);
        const serializedValue = JSON.stringify(value);

        if (ttl) {
            await this.redis.setex(redisKey, ttl, serializedValue);
        } else {
            await this.redis.set(redisKey, serializedValue);
        }
    }

    async get<T = any>(key: string): Promise<T | null> {
        const redisKey = this.getKey(key);
        const data = await this.redis.get(redisKey);

        if (!data) return null;

        try {
            return JSON.parse(data);
        } catch {
            return data as T;
        }
    }

    async delete(key: string): Promise<void> {
        const redisKey = this.getKey(key);
        await this.redis.del(redisKey);
    }

    async deletePattern(pattern: string): Promise<void> {
        const redisPattern = this.getKey(pattern);
        const keys = await this.redis.keys(redisPattern);

        if (keys.length > 0) {
            await this.redis.del(...keys);
        }
    }

    async exists(key: string): Promise<boolean> {
        const redisKey = this.getKey(key);
        const result = await this.redis.exists(redisKey);
        return result === 1;
    }

    async expire(key: string, ttl: number): Promise<void> {
        const redisKey = this.getKey(key);
        await this.redis.expire(redisKey, ttl);
    }
} 