import { Args } from '@oclif/core';
import { fromBasedString } from '@trebuchet/sdk-nodejs';
import { webcrypto as crypto } from 'node:crypto';
import { readFile } from 'node:fs/promises';
import { BaseCommand, REQUEST_PARTIAL_ID } from '../../base.js';
export default class RequestImportKey extends BaseCommand {
    static args = {
        id: REQUEST_PARTIAL_ID,
        keyfile: Args.file({
            description: 'Path to backup file created by the web application',
            required: true,
        }),
    };
    static description = 'Import keys for an existing sharing request to enable file download.';
    static enableJsonFlag = true;
    async run() {
        const res = await this.matchInvite(this.args.id);
        const backup = JSON.parse(await readFile(this.args.keyfile, { encoding: 'utf8' }));
        if (backup.id !== res.publicId) {
            throw new Error(`Incorrect sharing request backup file for ID ${res.publicId}`);
        }
        const key = await crypto.subtle.unwrapKey('raw', fromBasedString('base64-url', backup.ekey), this.kek, {
            name: 'AES-KW',
        }, { name: 'AES-GCM' }, false, ['encrypt', 'decrypt']);
        const data = await crypto.subtle.decrypt({
            iv: fromBasedString('base64-url', backup.iv),
            name: 'AES-GCM',
            tagLength: 128,
        }, key, fromBasedString('base64-url', backup.edata));
        // eslint-disable-next-line camelcase
        const { private_key } = JSON.parse(new TextDecoder().decode(data));
        // eslint-disable-next-line camelcase
        this.setInvite(res.publicId, { private_key });
        this.log(`Private key imported successfully.`);
        return { success: true };
    }
}
