"use strict";
var __importDefault = (this && this.__importDefault) || function (mod) {
    return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.send = send;
const actions_core_1 = require("@segment/actions-core");
const btoa_lite_1 = __importDefault(require("btoa-lite"));
async function send(request, payloads, settings) {
    const { host, port, username, password, dbName, tableName } = settings;
    const url = `https://${host}:${port}/api/v2/exec`;
    const encodedCredentials = (0, btoa_lite_1.default)(`${username}:${password}`);
    const columns = [
        'messageId',
        'timestamp',
        'type',
        'event',
        'name',
        'properties',
        'userId',
        'anonymousId',
        'groupId',
        'traits',
        'context'
    ];
    const sqlValuesClause = payloads.map(() => `(${columns.map(() => '?').join(', ')})`).join(', ');
    const sql = `INSERT INTO \`${tableName.replace(/`/g, '``')}\` (${columns.join(', ')}) VALUES ${sqlValuesClause}`;
    function toUTCDateTime(timestamp) {
        return timestamp.replace('T', ' ').replace('Z', '');
    }
    const argsTuples = payloads.map((item) => [
        item.messageid,
        toUTCDateTime(item.timestamp),
        item.type,
        item.event ?? null,
        item.name ?? null,
        item.properties ?? null,
        item.userId ?? null,
        item.anonymousId ?? null,
        item.groupId ?? null,
        item.traits ?? null,
        item.context ?? null
    ]);
    const args = argsTuples.flat();
    const requestData = {
        sql,
        database: dbName,
        args
    };
    const response = await request(url, {
        method: 'POST',
        headers: {
            'Content-Type': 'application/json',
            Authorization: `Basic ${encodedCredentials}`
        },
        json: requestData,
        throwHttpErrors: false
    });
    if (response.status !== 200 || response.ok === false) {
        throw new actions_core_1.IntegrationError(`Failed to insert data: ${(await response.text()) || 'Unknown error'}`, response.statusText, response.status);
    }
    return response;
}
//# sourceMappingURL=utils.js.map