import { fromRandom, toBasedString } from '@trebuchet/sdk-nodejs';
import { webcrypto as crypto } from 'node:crypto';
import { writeFile } from 'node:fs/promises';
import { BaseCommand, REQUEST_PARTIAL_ID } from '../../base.js';
export default class RequestExportKey extends BaseCommand {
    static args = {
        id: REQUEST_PARTIAL_ID,
    };
    static description = 'Export keys for an existing sharing request to enable file download from a browser.';
    static enableJsonFlag = true;
    async run() {
        const res = await this.matchInvite(this.args.id);
        const meta = await this.getInvite(res.publicId);
        const iv = fromRandom(12);
        const key = await crypto.subtle.generateKey({
            name: 'AES-GCM',
            length: 256,
        }, true, ['encrypt', 'decrypt']);
        const ekey = await crypto.subtle.wrapKey('raw', key, this.kek, {
            name: 'AES-KW',
        });
        const ekeyB64 = toBasedString('base64-url', ekey);
        const backup = {
            id: res.publicId,
            ekey: ekeyB64,
            iv: toBasedString('base64-url', iv),
            edata: toBasedString('base64-url', await crypto.subtle.encrypt({
                name: 'AES-GCM',
                iv,
                tagLength: 128,
            }, key, new TextEncoder().encode(JSON.stringify({
                id: res.publicId,
                ...meta,
            })))),
        };
        await writeFile(`backup.${res.publicId}.json`, JSON.stringify(backup));
        this.log(`Private key exported successfully.`);
        return { success: true };
    }
}
