// Core dependencies
import { BN, Program } from "@coral-xyz/anchor";
import { PublicKey, TransactionInstruction } from "@solana/web3.js";

// Local imports
import { BasketsProgram } from "../../idl/types";
import { MAX_SUPPORTED_TOKENS_V200 } from "../../utils/constants";


export async function updateTokenWeightsIx(params: {
    program: Program<BasketsProgram>;
    basket: PublicKey;
    manager: PublicKey;
    tokenWeights: number[];
    writeVersion: number;
}): Promise<TransactionInstruction> {
    // Destructure params
    const { program, basket, manager, tokenWeights, writeVersion } = params;

    // Pad token weights array with zeros if needed
    const paddedTokenWeights = [...tokenWeights];
    while (paddedTokenWeights.length < MAX_SUPPORTED_TOKENS_V200) {
        paddedTokenWeights.push(0);
    }

    // Build and return instruction
    return await program.methods
        .updateTokenWeights(
            paddedTokenWeights,
            new BN(writeVersion)
        )
        .accountsStrict({
            manager,
            basket,
        })
        .instruction();
}
