import { Connection, TransactionInstruction, PublicKey } from "@solana/web3.js";
import { MAX_ATA_CREATION_PER_TX } from "./constants";
import { getAccountInfos, getAta } from "./programAccounts";
import { createAssociatedTokenAccountInstruction } from "@solana/spl-token";


export async function createAtasIxs(
    connection: Connection,
    params: {
        payer: PublicKey,
        mints: PublicKey[],
    }
): Promise<TransactionInstruction[][]> {
    const { mints, payer } = params;
    const uniqueMints = [...new Set(mints.map(mint => mint.toBase58()))].map(mint => new PublicKey(mint));
    const accountDatas = await getAccountInfos(connection, uniqueMints.map(mint => getAta(payer, mint)));
    const preIxsAll: TransactionInstruction[] = [];
    accountDatas.forEach((accountData, i) => {
        if (!accountData) {
            preIxsAll.push(createAssociatedTokenAccountInstruction(
                payer,
                getAta(payer, uniqueMints[i]),
                payer,
                uniqueMints[i],
            ));
        }
    });
    const preIxs: TransactionInstruction[][] = [];
    for (let i = 0; i < preIxsAll.length; i += MAX_ATA_CREATION_PER_TX)
        preIxs.push(preIxsAll.slice(i, i + MAX_ATA_CREATION_PER_TX));
    return preIxs;
}
