
import { uuid } from '../utils.mjs';
import { Role } from './doc-user-role.mjs';
import { db } from './config.mjs';

export class DocShareLinkDb {
    get(docId: string): Promise<IDocShareLink | undefined> {
        return new Promise((resolve, reject) => {
            db.get<IDocShareLinkRecord>('SELECT * FROM document_share_link WHERE doc_id = ?', [docId], (err, row) => {
                if (err) {
                    console.error(err);
                    return reject(err);
                }

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

    insert(link: string, docId: string, role: Role): Promise<IDocShareLink> {
        return new Promise((resolve, reject) => {
            const id = uuid();

            db.run('INSERT INTO document_share_link (link, doc_id, role) VALUES (?, ?, ?)', [link, docId, role], (err) => {
                if (err) {
                    console.error(err);
                    return reject('internal error: insert error');
                }

                resolve({ link, docId, role });
            });
        });
    }
}

interface IDocShareLinkRecord {
    link: string;
    doc_id: string;
    role: Role;
}

export interface IDocShareLink {
    link: string;
    docId: string;
    role: Role;
}

function convert(r: IDocShareLinkRecord): IDocShareLink {
    return { docId: r.doc_id, ...r };
}