import { Injectable } from '@nestjs/common';
import { RedisService } from '../../infra/redis.service';

export type RegisteredCallbackQuery = {
  userId: string;
  botId: string;
  callbackData: string;
  messageId: number;
  chatId: number;
};

@Injectable()
export class BotCallbackRegistryService {
  constructor(private readonly redis: RedisService) {}

  private key(callbackQueryId: string) {
    return `bot:callback:${callbackQueryId}`;
  }

  async register(callbackQueryId: string, payload: RegisteredCallbackQuery) {
    await this.redis.client.set(this.key(callbackQueryId), JSON.stringify(payload), 'EX', 3600);
  }

  async resolve(callbackQueryId: string) {
    const raw = await this.redis.client.get(this.key(callbackQueryId));
    if (!raw) return null;
    try {
      return JSON.parse(raw) as RegisteredCallbackQuery;
    } catch {
      return null;
    }
  }
}
