import { Injectable, Logger } from '@nestjs/common'; import { ConfigService } from '@nestjs/config'; import Redis from 'ioredis'; import { ConversationEntry } from './types'; @Injectable() export class MessagingConversationService { private readonly logger = new Logger(MessagingConversationService.name); private readonly redis: Redis; private readonly ttlSec = 24 * 60 * 60; // 24h — matches WhatsApp session window private readonly maxHistory = 20; constructor(config: ConfigService) { const redisUrl = config.get('redis.url') ?? 'redis://localhost:6379'; this.redis = new Redis(redisUrl); } private key(phone: string): string { return `wa:conv:${phone}`; } async getHistory(phone: string): Promise { const raw = await this.redis.get(this.key(phone)); if (!raw) return []; try { return JSON.parse(raw); } catch { return []; } } async addMessages(phone: string, entries: ConversationEntry[]): Promise { const existing = await this.getHistory(phone); const updated = [...existing, ...entries].slice(-this.maxHistory); await this.redis.setex(this.key(phone), this.ttlSec, JSON.stringify(updated)); } async clear(phone: string): Promise { await this.redis.del(this.key(phone)); } }