#!/usr/bin/env node
"use strict";
const { Connection, PublicKey, Transaction, sendAndConfirmTransaction } = require("@solana/web3.js");
const { TOKEN_2022_PROGRAM_ID, AuthorityType, createSetAuthorityInstruction } = require("@solana/spl-token");
const { parseEnvConfig, assertRequired, resolveConfigPath, parseCluster, askYes, ui, getMintPublicKeyFromConfig, getOperatorKeypairFromConfig } = require("./_common");

async function main() {
  const cfg = parseEnvConfig(resolveConfigPath(process.argv[2]));
  assertRequired(cfg, "GT_CLUSTER"); assertRequired(cfg, "GT_GOVERNANCE_PDA");
  const mint = getMintPublicKeyFromConfig(cfg);
  const operator = getOperatorKeypairFromConfig(cfg);
  const governancePda = new PublicKey(cfg.GT_GOVERNANCE_PDA);
  const connection = new Connection(parseCluster(cfg.GT_CLUSTER), "confirmed");
  ui.title("=== Передача прав DAO / Transfer rights to DAO ===");
  ui.warn(`RU: Будут переданы права Mint/Freeze/PermanentDelegate от ${operator.publicKey.toBase58()} на ${governancePda.toBase58()}`);
  ui.warn(`EN: Mint/Freeze/PermanentDelegate authorities will be transferred to governance PDA.`);
  const ok = await askYes("Введите yes / Type yes to continue: ");
  if (!ok) return ui.warn("Отменено / Cancelled");
  const ixs = [
    createSetAuthorityInstruction(mint, operator.publicKey, AuthorityType.MintTokens, governancePda, [], TOKEN_2022_PROGRAM_ID),
    createSetAuthorityInstruction(mint, operator.publicKey, AuthorityType.FreezeAccount, governancePda, [], TOKEN_2022_PROGRAM_ID),
    createSetAuthorityInstruction(mint, operator.publicKey, AuthorityType.PermanentDelegate, governancePda, [], TOKEN_2022_PROGRAM_ID),
  ];
  const sig = await sendAndConfirmTransaction(connection, new Transaction().add(...ixs), [operator], { commitment: "confirmed" });
  ui.ok("Успешно / Success");
  ui.info(`Mint: ${mint.toBase58()}`); ui.info(`DAO PDA: ${governancePda.toBase58()}`); ui.info(`Tx: ${sig}`);
}
main().catch((e) => { ui.err(`Ошибка / Error: ${e?.message || e}`); process.exit(1); });
