import Dexie, { type Table } from 'dexie';

export interface ChatMessage {
    id?: number;
    sessionId: string;  // Story 3.2: Added sessionId for cascade delete
    role: 'user' | 'assistant';
    content: string;
    timestamp: number;
    intent?: 'venting' | 'insight';
}

export interface DraftRecord {
    id?: number;
    sessionId: string;
    title: string;
    content: string;      // Markdown formatted
    tags: string[];       // Array of tag strings
    createdAt: number;
    status: 'draft' | 'completed' | 'regenerated';
    completedAt?: number; // Story 2.4: Completion timestamp
}

/**
 * SyncQueueItem Interface
 * Story 3.3: Offline sync queue for actions to be synchronized
 */
export interface SyncQueueItem {
    id?: number;
    action: 'saveDraft' | 'deleteDraft' | 'completeDraft';
    payload: {
        draftId?: number;
        draftData?: Omit<DraftRecord, 'id'>;
        sessionId?: string;
    };
    status: 'pending' | 'processing' | 'synced' | 'failed';
    createdAt: number;
    retries: number;
    lastError?: string;
}

export class ChatDatabase extends Dexie {
    chatLogs!: Table<ChatMessage>;
    drafts!: Table<DraftRecord>;
    syncQueue!: Table<SyncQueueItem>;

    constructor() {
        super('Test01Database');

        // Version 1: Initial schema with chatLogs
        this.version(1).stores({
            chatLogs: '++id, timestamp',
        });

        // Version 2: Add sessionId index for cascade delete (Story 3.2)
        this.version(2).stores({
            chatLogs: '++id, sessionId, timestamp',
            drafts: '++id, sessionId, createdAt, status',
        }).upgrade(tx => {
            // Migration: Add sessionId to existing chat logs
            return tx.table('chatLogs').toCollection().modify(chat => {
                if (!chat.sessionId) {
                    chat.sessionId = 'legacy-' + chat.timestamp;
                }
            });
        });

        // Version 3: Add SyncQueue table (Story 3.3)
        this.version(3).stores({
            chatLogs: '++id, sessionId, timestamp',
            drafts: '++id, sessionId, createdAt, status',
            syncQueue: '++id, status, createdAt', // Indexed for efficient queries
        }).upgrade(() => {
            // No data migration needed - new empty table
            console.log('Database upgraded to v3: SyncQueue added');
        });

        // Version 4: Add completedAt index for history feed (Story 3.1)
        this.version(4).stores({
            chatLogs: '++id, sessionId, timestamp',
            drafts: '++id, sessionId, createdAt, status, completedAt', // Added completedAt index
            syncQueue: '++id, status, createdAt',
        }).upgrade(() => {
            // No data migration needed - just adding index
            console.log('Database upgraded to v4: completedAt index added for history feed');
        });

        // Version 5: Add compound index for performant sorting (Story 3.1 Fix)
        this.version(5).stores({
            chatLogs: '++id, sessionId, timestamp',
            drafts: '++id, sessionId, createdAt, status, completedAt, [status+completedAt]',
            syncQueue: '++id, status, createdAt',
        }).upgrade(() => {
            console.log('Database upgraded to v5: [status+completedAt] compound index added');
        });
    }
}

export const db = new ChatDatabase();

if (typeof window !== 'undefined') {
    (window as any).db = db;
}
