import { dev } from '$app/environment';
import getPoolSize from './getPoolSize';

// Based on code generated by Claude 3.5 Sonnet
class QuestionBalanceStore {
	private balances: Map<string, number>;
	private lastAccessed: Map<string, number>;

	constructor() {
		this.balances = new Map();
		this.lastAccessed = new Map();

		// Clean up expired sessions every hour
		setInterval(() => this.cleanup(), 1000 * 60 * 60);
	}

	// Get remaining questions for a session
	getBalance(sessionToken: string): number {
		this.lastAccessed.set(sessionToken, Date.now());
		return this.balances.get(sessionToken) || 0;
	}

	// Add questions to a session (e.g., after answering)
	addQuestions(sessionToken: string, count: number = 1): void {
		this.lastAccessed.set(sessionToken, Date.now());

		const currentBalance = this.balances.get(sessionToken) || 0;
		this.balances.set(sessionToken, currentBalance + count);
	}

	// Use a question from the balance
	async useQuestion(sessionToken: string): Promise<boolean> {
		this.lastAccessed.set(sessionToken, Date.now());

		const currentBalance = this.balances.get(sessionToken) || 0;

		// New users can neither ask nor answer in this case
		// Allow one question for this edge case
		if (currentBalance === 0) {
			const poolSize = await getPoolSize();
			return poolSize === 0;
		}

		this.balances.set(sessionToken, currentBalance - 1);
		return true;
	}

	// Clean up sessions that haven't been accessed in 24 hours
	private cleanup(): void {
		const now = Date.now();
		const expiryTime = 24 * 60 * 60 * 1000; // 24 hours

		for (const [token, lastAccess] of this.lastAccessed.entries()) {
			if (now - lastAccess > expiryTime) {
				this.balances.delete(token);
				this.lastAccessed.delete(token);
			}
		}
	}

	// For debugging in development
	debugInfo(): unknown {
		if (!dev) return null;
		return {
			totalSessions: this.balances.size,
			sessions: Object.fromEntries(this.balances),
			lastAccessed: Object.fromEntries(this.lastAccessed)
		};
	}
}

// Create singleton instance
export const questionBalanceStore = new QuestionBalanceStore();
