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

export class DocDb {
    get(id: string): Promise<IDoc | undefined> {
        return new Promise((resolve, reject) => {
            db.get<IDocRecord>('SELECT * FROM documents_ex WHERE id = ?', [id], (err, row) => {
                if (err) {
                    console.error(err);
                    return reject(err);
                }

                resolve(row ? convertToDoc(row) : undefined);
            });
        });
    }

    rename(docId: string, name: string) {
        return new Promise((resolve, reject) => {
            db.run('UPDATE documents_ex SET name = ? WHERE id = ?', [name, docId], (err: any, row: IDocRecord) => {
                if (err) {
                    console.error(err);
                    return reject(err);
                }

                resolve(row ? convertToDoc(row) : undefined);
            });
        });
    }

    updateLastModifyInfo(docId: string, userId: string): Promise<void> {
        return new Promise((resolve, reject) => {
            db.run(`UPDATE documents_ex SET last_modify_user_id = ?, last_modify_date = datetime('now') WHERE id = ?`, [userId, docId], (err) => {
                if (err) {
                    console.error(err);
                    return reject('internal error: insert doc error');
                }

                resolve();
            });
        });
    }

    insert(name: string, type: string, createUserId: string): Promise<IDoc> {
        return new Promise((resolve, reject) => {
            const id = uuid();
            db.run(`INSERT INTO documents_ex (id, name, type, create_user_id, last_modify_user_id, last_modify_date) VALUES (?, ?, ?, ?, ?, datetime('now'))`, [id, name, type, createUserId, createUserId], (err) => {
                if (err) {
                    console.error(err);
                    return reject('internal error: insert doc error');
                }

                this.get(id).then(d => resolve(d as IDoc)).catch(reject);
            });
        });
    }

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

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

export interface IDoc {
    id: string;
    name: string;
    type: string;
    createUserId: string;
    lastModifyUserId: string;
    lastModifyDate: string;
}

interface IDocRecord {
    id: string;
    name: string;
    type: string;
    create_user_id: string;
    last_modify_user_id: string;
    last_modify_date: string;
}

function convertToDoc(d: IDocRecord): IDoc {
    return {
        ...d,
        createUserId: d.create_user_id,
        lastModifyUserId: d.last_modify_user_id,
        lastModifyDate: d.last_modify_date
    };
}