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

// Local imports
import { BasketsProgram } from "../../idl/types";
import { WITHDRAW_STATE_SIZE } from "../../state/withdrawState";
import { getStateCreatorAccount, getWithdrawStateAccount } from "../../utils/programAccounts";


export async function initializeWithdrawStateIx(params: {
    program: Program<BasketsProgram>;
    withdrawStateSeed: number[];
}) {
    // Destructure params
    const { program, withdrawStateSeed } = params;

    // Calculate required lamports for rent exemption
    const lamports = await program.provider.connection.getMinimumBalanceForRentExemption(
        8 + WITHDRAW_STATE_SIZE
    );

    // Get required accounts
    const withdrawState = getWithdrawStateAccount(withdrawStateSeed);
    const stateCreator = getStateCreatorAccount();

    // Build and return instruction
    return await program.methods
        .initializeWithdrawState(
            withdrawStateSeed,
            new BN(lamports)
        )
        .accountsStrict({
            withdrawState,
            stateCreator,
            systemProgram: SystemProgram.programId,
            rent: SYSVAR_RENT_PUBKEY,
        })
        .instruction();
}
