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

async function main() {
  const cfg = parseEnvConfig(resolveConfigPath(process.argv[2]));
  const receiver = new PublicKey(process.argv[3]);
  if (!process.argv[3]) throw new Error("Использование / Usage: node .../02...js <config.env> <receiver_wallet>");
  assertRequired(cfg, "GT_CLUSTER");
  const mint = getMintPublicKeyFromConfig(cfg);
  const operator = getOperatorKeypairFromConfig(cfg);
  const connection = new Connection(parseCluster(cfg.GT_CLUSTER), "confirmed");
  const ata = getAssociatedTokenAddressSync(mint, receiver, false, TOKEN_2022_PROGRAM_ID);
  const ataInfo = await connection.getAccountInfo(ata, "confirmed");
  if (ataInfo) {
    const tokenAcc = await getAccount(connection, ata, "confirmed", TOKEN_2022_PROGRAM_ID);
    if (tokenAcc.amount >= 1n) {
      throw new Error(
        `На кошельке уже есть membership token / Wallet already has membership token. wallet=${receiver.toBase58()} amount=${tokenAcc.amount.toString()}`
      );
    }
  }
  const ix = [
    createAssociatedTokenAccountIdempotentInstruction(operator.publicKey, ata, receiver, mint, TOKEN_2022_PROGRAM_ID),
    createMintToInstruction(mint, ata, operator.publicKey, 1n, [], TOKEN_2022_PROGRAM_ID),
  ];
  ui.title("=== Выпуск 1 membership токена / Mint 1 membership token ===");
  const sig = await sendAndConfirmTransaction(connection, new Transaction().add(...ix), [operator], { commitment: "confirmed" });
  ui.ok("Успешно / Success");
  ui.info(`Mint: ${mint.toBase58()}`); ui.info(`Wallet: ${receiver.toBase58()}`); ui.info(`Tx: ${sig}`);
}
main().catch((e) => { ui.err(`Ошибка / Error: ${e?.message || e}`); process.exit(1); });
