import { hsm } from "@dinamonetworks/hsm-dinamo";

// Define os parâmetros de conexão com o HSM
const options = {
host: "127.0.0.1",
authUsernamePassword: {
username: "master",
password: "12345678",
},
};

// Define o usuário para criar e usar nos métodos
const USER_ID = "myUserTest";
const USER_PASSWORD = "12345678";

async function main() {
let conn;

try {
// Conecta ao HSM
conn = await hsm.connect(options);

// Cria o usuário
try {
const permissions = [
hsm.enums.USER_PERMISSIONS.NS_AUTHORIZATION,
hsm.enums.USER_PERMISSIONS.SYS_OPERATOR,
];

const created = await conn.user.create(
USER_ID,
USER_PASSWORD,
permissions
);

if (created) {
console.log(`User "${USER_ID}" created successfully`);
} else {
console.log(`Failed to create user "${USER_ID}"`);
}
} catch (error) {
console.error("Error creating user:", error.message);
throw error;
}

await conn.disconnect();

const optNsAuth = {
host: "127.0.0.1",
authUsernamePassword: {
username: USER_ID,
password: USER_PASSWORD,
},
};

conn = await hsm.connect(optNsAuth);

// PINs dos smartcards a serem inseridos
const pin1 = "12345678"; // Substitua pelo PIN real do primeiro smartcard
const pin2 = "12345678"; // Substitua pelo PIN real do segundo smartcard

// Obtém shadows dos smartcards
console.log("Insert the first smartcard...");

let shadow1;

try {
shadow1 = await conn.management.getShadow(pin1);
console.log(`Shadow retrieved: ${shadow1}`);
} catch (error) {
console.error("Error retrieving shadow:", error.message);
throw error;
}

console.log("Please replace the smartcard with the second one...");

// Aguarda a troca do smartcard
await new Promise((resolve) => setTimeout(resolve, 10000)); // Espera de 10 segundos

console.log("Insert the second smartcard...");

let shadow2;

try {
shadow2 = await conn.management.getShadow(pin2);
console.log(`Shadow retrieved: ${shadow2}`);
} catch (error) {
console.error("Error retrieving shadow:", error.message);
throw error;
}

// Adiciona as shadows em um array de shadows
const shadows = [shadow1, shadow2];

// Define o estado NS Auth
try {
const aclMask = hsm.enums.ACL_MASK.NOP;
const state = hsm.enums.NSAUTH_STATE.ASSOCIATED;

const result = await conn.management.setNsAuthState(
aclMask,
state,
shadows
);

console.log(`Set NS Auth State result: ${result}`);

if (result) {
console.log("NS Auth State set successfully.");
} else {
console.log("Failed to set NS Auth State.");
}
} catch (error) {
console.error("Error setting NS Auth State:", error.message);
throw error;
}
} catch (error) {
console.error("An error occurred:", error.message);
} finally {
if (conn) {
// Desconecta do HSM
await conn.disconnect();
}
}
}

// Executa a função principal
main();