import type { IStorageService } from './storage/IStorageService'; import type { WidgetSamplerLog } from '../domain'; export type TimestampField = keyof Pick; export class WidgetStateManager { private storageService: IStorageService; private storageKey: string; constructor(storageService: IStorageService, storageKey: string) { this.storageService = storageService; this.storageKey = storageKey; } async getLogs(): Promise { try { return await this.storageService.read(this.storageKey); } catch (error) { console.error('[WidgetStateManager] Error reading logs:', error); return this.getDefaultLogs(); } } async incrementAttempt(): Promise { const logs = await this.getLogs(); const updatedLogs: WidgetSamplerLog = { ...logs, attempts: (logs.attempts || 0) + 1, }; await this.storageService.write(this.storageKey, updatedLogs); return updatedLogs; } async saveLogs(logs: WidgetSamplerLog): Promise { await this.storageService.write(this.storageKey, logs); } async resetAttempts(): Promise { const logs = await this.getLogs(); const updatedLogs: WidgetSamplerLog = { ...logs, attempts: 0, }; await this.storageService.write(this.storageKey, updatedLogs); return updatedLogs; } async hasAnsweredTransaction(transactionId?: string): Promise { if (!transactionId) { return false; } const logs = await this.getLogs(); return (logs.answeredTransactionIds || []).includes(transactionId); } async markTransactionAnswered(transactionId?: string): Promise { const logs = await this.getLogs(); if (!transactionId) { return logs; } const answeredTransactionIds = logs.answeredTransactionIds || []; if (answeredTransactionIds.includes(transactionId)) { return logs; } const updatedLogs: WidgetSamplerLog = { ...logs, answeredTransactionIds: [...answeredTransactionIds, transactionId], }; await this.storageService.write(this.storageKey, updatedLogs); return updatedLogs; } async updateTimestamp(field: TimestampField): Promise { const logs = await this.getLogs(); const updatedLogs: WidgetSamplerLog = { ...logs, [field]: Date.now(), }; await this.storageService.write(this.storageKey, updatedLogs); } async overrideTimestamp(field: TimestampField, date: Date | number): Promise { const logs = await this.getLogs(); const timestamp = date instanceof Date ? date.getTime() : date; const updatedLogs: WidgetSamplerLog = { ...logs, [field]: timestamp, }; await this.storageService.write(this.storageKey, updatedLogs); } async clearLogs(): Promise { await this.storageService.delete(this.storageKey); } async hasLogs(): Promise { return await this.storageService.exists(this.storageKey); } private getDefaultLogs(): WidgetSamplerLog { return { attempts: 0, answeredTransactionIds: [], }; } }