import type { GameSessionStore, GameSessionData } from "./GameSessionStore.js";

type SessionEntry = { data: GameSessionData; expiresAt: number };

export class InMemoryGameSessionStore implements GameSessionStore {
  private sessions = new Map<string, SessionEntry>();

  create(
    sessionId: string,
    data: GameSessionData,
    ttlMs: number,
  ): Promise<void> {
    this.sessions.set(sessionId, { data, expiresAt: Date.now() + ttlMs });
    return Promise.resolve();
  }

  get(sessionId: string): Promise<GameSessionData | null> {
    const entry = this.sessions.get(sessionId);
    if (!entry) return Promise.resolve(null);
    if (Date.now() > entry.expiresAt) {
      this.sessions.delete(sessionId);
      return Promise.resolve(null);
    }
    return Promise.resolve(entry.data);
  }

  update(sessionId: string, data: GameSessionData): Promise<void> {
    const entry = this.sessions.get(sessionId);
    if (!entry) return Promise.resolve();
    this.sessions.set(sessionId, { data, expiresAt: entry.expiresAt });
    return Promise.resolve();
  }

  delete(sessionId: string): Promise<void> {
    this.sessions.delete(sessionId);
    return Promise.resolve();
  }
}
