// @ts-check

interface SQLInsertGenReturn {
    query: string;
    values: string[];
}

/**
 * # SQL Insert Generator
 */
export default function sqlInsertGenerator({
    tableName,
    data,
    dbFullName,
}: {
    data: any[];
    tableName: string;
    dbFullName?: string;
}): SQLInsertGenReturn | undefined {
    const finalDbName = dbFullName ? `${dbFullName}.` : "";

    try {
        if (Array.isArray(data) && data?.[0]) {
            let insertKeys: string[] = [];

            data.forEach((dt) => {
                const kys = Object.keys(dt);
                kys.forEach((ky) => {
                    if (!insertKeys.includes(ky)) {
                        insertKeys.push(ky);
                    }
                });
            });

            /** @type {string[]} */
            let queryBatches: string[] = [];
            /** @type {string[]} */
            let queryValues: string[] = [];

            data.forEach((item) => {
                queryBatches.push(
                    `(${insertKeys
                        .map((ky) => {
                            queryValues.push(
                                item[ky]?.toString()?.match(/./)
                                    ? item[ky]
                                    : null
                            );
                            return "?";
                        })
                        .join(",")})`
                );
            });
            let query = `INSERT INTO ${finalDbName}${tableName} (${insertKeys.join(
                ","
            )}) VALUES ${queryBatches.join(",")}`;

            return {
                query: query,
                values: queryValues,
            };
        } else {
            return undefined;
        }
    } catch (/** @type {any} */ error: any) {
        console.log(`SQL insert gen ERROR: ${error.message}`);
        return undefined;
    }
}
