import { db } from './config.mjs';

export class OpsExDb {
    getByDocId(docId: string): Promise<IOpEx[]> {
        return new Promise((resolve, reject) => {
            db.all<IOpExRecord>('SELECT * FROM ops_ex WHERE doc_id = ?', [docId], (err, row) => {
                if (err) {
                    console.error(err);
                    return reject(err);
                }

                resolve(row.map(convert));
            });
        });
    } 

    insert(userId: string, docId: string, version: number): Promise<void> {
        return new Promise((resolve, reject) => {
            db.run(`INSERT INTO ops_ex (user_id, doc_id, version, date) VALUES (?, ?, ?, datetime('now'))`, [userId, docId, version], (err) => {
                if (err) {
                    console.error(err);
                    return reject('internal error: insert doc error');
                }

                resolve();
            });
        });
    }

    deleteByDocId(docId: string): Promise<void> {
        return new Promise((resolve, reject) => {
            db.run('DELETE FROM ops_ex WHERE doc_id = ?', [docId], (err: any) => {
                if (err) {
                    console.error(err);
                    return reject(err);
                }

                resolve();
            });
        });
    }
}

export interface IOpEx {
    userId: string;
    docId: string;
    version: number;
    date: string;
}

interface IOpExRecord {
    doc_id: string;
    version: number;
    user_id: string;
    date: string;
}

function convert(d: IOpExRecord): IOpEx {
    return { userId: d.user_id, docId: d.doc_id, version: d.version, date: d.date };
}