import {
    Buffer
} from "buffer";
import cryptoModule from "crypto";

const _global = typeof window !== "undefined" ? window : (typeof global !== "undefined" ? global : null);
if (_global) {
    (_global as Record<string, unknown>).Buffer = (_global as Record<string, unknown>).Buffer || Buffer;
    (_global as Record<string, unknown>).process = (_global as Record<string, unknown>).process || process;
}

if (typeof (cryptoModule as Record<string, unknown>).KeyObject === "undefined") {
    class KeyObject {
        type: string;
        key: unknown;
        constructor(type: string, key: unknown) {
            this.type = type;
            this.key = key;
        }
        export() {
            return this.key;
        }
    }

    Object.assign(cryptoModule, {
        createSecretKey: function(key: unknown) {
            const buf = (typeof key === "string" ? Buffer.from(key) : (Buffer.isBuffer(key) ? key : Buffer.from(String(key)))) as Buffer & { type: string, export: () => Buffer };
            buf.type = "secret";
            buf.export = () => buf;
            return buf;
        },
        createPrivateKey: function(key: unknown) {
            const keyObj = key as Record<string, unknown>;
            const keyStr = typeof key === "string" ? key : (keyObj?.key ? String(keyObj.key) : (keyObj?.toString ? String(keyObj.toString()) : ""));
            if (typeof keyStr === "string" && keyStr.includes("-----BEGIN ")) {
                const buf = Buffer.from(keyStr) as Buffer & { type: string, export: () => Buffer };
                buf.type = "private";
                buf.export = () => buf;
                return buf;
            }
            throw new Error("Invalid private key");
        },
        createPublicKey: function(key: unknown) {
            const keyObj = key as Record<string, unknown>;
            const keyStr = typeof key === "string" ? key : (keyObj?.key ? String(keyObj.key) : (keyObj?.toString ? String(keyObj.toString()) : ""));
            if (typeof keyStr === "string" && keyStr.includes("-----BEGIN ")) {
                const buf = Buffer.from(keyStr) as Buffer & { type: string, export: () => Buffer };
                buf.type = "public";
                buf.export = () => buf;
                return buf;
            }
            throw new Error("Invalid public key");
        },
        KeyObject
    });
}
