"use strict";
var __importDefault = (this && this.__importDefault) || function (mod) {
    return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.TextEmAllClient = void 0;
const axios_1 = __importDefault(require("axios"));
const crypto_js_1 = __importDefault(require("crypto-js"));
const oauth_1_0a_1 = __importDefault(require("oauth-1.0a"));
class TextEmAllClient {
    constructor(params) {
        const { customerKey, customerSecret, token } = params;
        // text-em-all uses the same url for both sandbox and production
        const baseUrl = 'https://rest.text-em-all.com/v1';
        this.token = token;
        this.customerSecret = customerSecret;
        // Initialize OAuth
        this.oauth = new oauth_1_0a_1.default({
            consumer: {
                key: customerKey,
                secret: customerSecret,
            },
            signature_method: 'HMAC-SHA1',
            hash_function(baseString, key) {
                return crypto_js_1.default.HmacSHA1(baseString, key).toString(crypto_js_1.default.enc.Base64);
            },
        });
        this.client = axios_1.default.create({
            baseURL: baseUrl,
            headers: {
                'Content-Type': 'application/json',
                Accept: 'application/json',
            },
        });
        // Add request interceptor to add OAuth headers
        this.client.interceptors.request.use((config) => {
            var _a, _b, _c;
            const url = `${baseUrl}${(_a = config.url) !== null && _a !== void 0 ? _a : ''}`;
            const requestData = {
                url,
                method: (_c = (_b = config.method) === null || _b === void 0 ? void 0 : _b.toUpperCase()) !== null && _c !== void 0 ? _c : 'GET',
                data: config.data,
            };
            const authHeader = this.oauth.toHeader(this.oauth.authorize(requestData, {
                key: this.token,
                secret: this.customerSecret,
            }));
            // Verify the header format matches Text-em-all's requirements
            if (!authHeader.Authorization.startsWith('OAuth ')) {
                throw new Error('Invalid OAuth header format');
            }
            config.headers.Authorization = authHeader.Authorization;
            return config;
        });
    }
    async createBroadcast(data) {
        try {
            const resp = await this.client.post('/broadcasts', data);
            return resp;
        }
        catch (error) {
            console.error('Text-em-all error', JSON.stringify(error));
            throw new Error(`Failed to create broadcast: ${error instanceof Error ? error.message : 'Unknown error'}`);
        }
    }
}
exports.TextEmAllClient = TextEmAllClient;
//# sourceMappingURL=client.js.map