import { Injectable } from '@nestjs/common';
import * as Redis from 'ioredis';
import { ConfigService } from '@nestjs/config';

@Injectable()
export class RedisService {
    private client: Redis.Redis;
    private redisOption: Redis.RedisOptions;

    constructor(private configService: ConfigService) {
        this.redisOption = {
            host: this.configService.get('REDIS_HOST'),
            port: this.configService.get('REDIS_PORT'),
            db: 1,
        };
        this.client = new Redis.Redis(this.redisOption); // Create a Redis client instance
    }

    async set(
        key: string,
        value: any,
        expirationSeconds = 60 * 60 * 24
    ): Promise<void> {
        await this.client.set(
            key,
            JSON.stringify(value),
            'EX',
            expirationSeconds
        );
    }

    async get(key: string): Promise<any> {
        const value = await this.client.get(key);
        if (value) {
            return JSON.parse(value);
        } else {
            return null;
        }
    }

    async incr(key: string): Promise<any> {
        const value = await this.client.incr(key);
        return value;
    }
}
