"use strict";
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
    function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
    return new (P || (P = Promise))(function (resolve, reject) {
        function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
        function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
        function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
        step((generator = generator.apply(thisArg, _arguments || [])).next());
    });
};
var __importDefault = (this && this.__importDefault) || function (mod) {
    return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
const axios_1 = __importDefault(require("axios"));
const fs_1 = require("fs");
const WhatsappOfficialAPI_1 = __importDefault(require("./WhatsappOfficialAPI"));
const path_1 = __importDefault(require("path"));
const util_1 = require("util");
const fs_2 = __importDefault(require("fs"));
const writeFileAsync = util_1.promisify(fs_1.writeFile);
function receiveWhatsAppMediaOfficialAPI(mediaId, phoneNumberId) {
    return __awaiter(this, void 0, void 0, function* () {
        try {
            const { data } = yield WhatsappOfficialAPI_1.default.get(`/${process.env.VERSION}/${mediaId}?phone_number_id=${phoneNumberId}`);
            if (data && (data === null || data === void 0 ? void 0 : data.url)) {
                const config = {
                    headers: {
                        Authorization: `Bearer ${process.env.TOKEN}`
                    },
                    responseType: "arraybuffer"
                };
                const filename = Date.now() + String(Math.floor(Math.random() * 1000));
                const response = yield axios_1.default.get(data.url, config);
                const ext = response.headers["content-type"].split("/")[1];
                const filename_ext = `${filename}.${ext}`;
                const destPath = path_1.default.join(__dirname, `..`, `..`, `..`, `..`, `public`, `${filename_ext}`);
                fs_2.default.writeFileSync(destPath, response.data);
                return filename_ext;
            }
        }
        catch (error) {
            console.log("There was an error on receiveWhatsAppMediaOfficialAPI: ", error);
        }
        return null;
    });
}
exports.default = receiveWhatsAppMediaOfficialAPI;
