import { Injectable } from '@nestjs/common';
import { AppCacheService } from './app-cache.service';

@Injectable()
export class FeedVersionService {
  private static readonly GLOBAL_VERSION_KEY = 'feed:global:version';

  constructor(private readonly cacheService: AppCacheService) {}

  async getGlobalVersion(): Promise<number> {
    const current = await this.cacheService.get<number>(FeedVersionService.GLOBAL_VERSION_KEY);
    if (typeof current === 'number' && current > 0) {
      return current;
    }

    await this.cacheService.set(FeedVersionService.GLOBAL_VERSION_KEY, 1);
    return 1;
  }

  async bumpGlobalVersion(): Promise<number> {
    return this.cacheService.incr(FeedVersionService.GLOBAL_VERSION_KEY);
  }

  async getUserVersion(userId: string): Promise<number> {
    const key = `feed:user:${userId}:version`;
    const current = await this.cacheService.get<number>(key);
    if (typeof current === 'number' && current > 0) return current;
    await this.cacheService.set(key, 1);
    return 1;
  }

  async bumpUserVersion(userId: string): Promise<number> {
    return this.cacheService.incr(`feed:user:${userId}:version`);
  }
}
