import type { AuthorizationRequest } from '../types';
import type { StorageAdapter } from '../storage';

/**
 * 会话数据接口
 */
interface SessionData {
    session_id: string;
    user_id: string;
    client_id: string;
    created_at: number;
    auth_params?: AuthorizationRequest;
}

/**
 * 会话管理器
 * 处理用户会话的存储业务逻辑
 */
export class SessionManager {
    constructor(private storage: StorageAdapter, private sessionTTL: number = 3600) { }

    private getKey(sessionId: string): string {
        return `session:${sessionId}`;
    }

    /**
     * 生成唯一的会话ID
     */
    private generateSessionId(): string {
        return Math.random().toString(36).substring(2) + Date.now().toString(36);
    }

    /**
     * 创建新会话
     */
    async createSession(
        userId: string,
        clientId: string,
        authParams?: AuthorizationRequest
    ): Promise<SessionData> {
        const sessionId = this.generateSessionId();
        const sessionData: SessionData = {
            session_id: sessionId,
            user_id: userId,
            client_id: clientId,
            created_at: Date.now(),
            auth_params: authParams,
        };

        await this.storeSession(sessionId, sessionData);
        return sessionData;
    }

    /**
     * 销毁会话
     */
    async destroySession(sessionId: string): Promise<void> {
        await this.deleteSession(sessionId);
    }

    async storeSession(sessionId: string, data: any): Promise<void> {
        const key = this.getKey(sessionId);
        await this.storage.set(key, data, this.sessionTTL);
    }

    async getSession(sessionId: string): Promise<any> {
        const key = this.getKey(sessionId);
        return await this.storage.get(key);
    }

    async deleteSession(sessionId: string): Promise<void> {
        const key = this.getKey(sessionId);
        await this.storage.delete(key);
    }

    async updateSession(sessionId: string, updates: any): Promise<void> {
        const existingSession = await this.getSession(sessionId);
        if (existingSession) {
            const updatedSession = { ...existingSession, ...updates };
            await this.storeSession(sessionId, updatedSession);
        }
    }
} 