"use strict";
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
    if (k2 === undefined) k2 = k;
    var desc = Object.getOwnPropertyDescriptor(m, k);
    if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
      desc = { enumerable: true, get: function() { return m[k]; } };
    }
    Object.defineProperty(o, k2, desc);
}) : (function(o, m, k, k2) {
    if (k2 === undefined) k2 = k;
    o[k2] = m[k];
}));
var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
    Object.defineProperty(o, "default", { enumerable: true, value: v });
}) : function(o, v) {
    o["default"] = v;
});
var __importStar = (this && this.__importStar) || function (mod) {
    if (mod && mod.__esModule) return mod;
    var result = {};
    if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
    __setModuleDefault(result, mod);
    return result;
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.getLatestEmailDetails = exports.getGmailMessages = exports.getGmailMessagesWithRetry = exports.getGoogleAccessToken = void 0;
const test_1 = require("@playwright/test");
const console = __importStar(require("node:console"));
const sleep_1 = require("./sleep");
async function getGoogleAccessToken() {
    const tokenUrl = 'https://oauth2.googleapis.com/token';
    const context = await test_1.request.newContext();
    const response = await context.post(tokenUrl, {
        form: {
            client_id: process.env.GOOGLE_OATH_CLIENT_ID,
            grant_type: 'refresh_token',
        },
    });
    const responseBody = await response.json();
    (0, test_1.expect)(responseBody).toHaveProperty('access_token');
    (0, test_1.expect)(responseBody.access_token).not.toBeFalsy();
    return responseBody.access_token;
}
exports.getGoogleAccessToken = getGoogleAccessToken;
async function getGmailMessagesWithRetry(token, sender, diagramName, laterThan, maxRetries = 5) {
    for (let attempt = 0; attempt < maxRetries; attempt++) {
        try {
            const messages = await getGmailMessages(token, sender, diagramName, laterThan);
            (0, test_1.expect)(messages.length).toBe(1);
            return messages;
        }
        catch (error) {
            if (attempt < maxRetries - 1) {
                console.warn(`Attempt ${attempt + 1} failed for finding alert email ${diagramName}. Retrying...`);
                await (0, sleep_1.sleep)(60000);
            }
            else {
                throw new Error(`Failed to find email for ${diagramName} failed after ${maxRetries} attempts`);
            }
        }
    }
}
exports.getGmailMessagesWithRetry = getGmailMessagesWithRetry;
async function getGmailMessages(token, sender, diagramName, laterThan) {
    const context = await test_1.request.newContext({
        extraHTTPHeaders: {
            Authorization: `Bearer ${token}`,
        },
    });
    let url = `https://www.googleapis.com/gmail/v1/users/me/messages?q=from:${sender} "${diagramName}"`;
    if (laterThan) {
        url = ` ${url} after:${laterThan}`;
    }
    console.log(url);
    const response = await context.get(url);
    const responseBody = await response.json();
    (0, test_1.expect)(responseBody).toHaveProperty('messages');
    (0, test_1.expect)(responseBody.messages).not.toBeFalsy();
    return responseBody.messages;
}
exports.getGmailMessages = getGmailMessages;
async function getLatestEmailDetails(token, emailId) {
    const context = await test_1.request.newContext({
        extraHTTPHeaders: {
            Authorization: `Bearer ${token}`,
        },
    });
    const response = await context.get(`https://www.googleapis.com/gmail/v1/users/me/messages/${emailId}`);
    const data = await response.json();
    let body = 'No body available';
    if (data.payload.parts) {
        const part = data.payload.parts.find((p) => p.mimeType === 'text/plain');
        if (part && part.body.data) {
            body = Buffer.from(part.body.data, 'base64').toString('utf-8');
        }
    }
    else if (data.payload.body.data) {
        body = Buffer.from(data.payload.body.data, 'base64').toString('utf-8');
    }
    return body;
}
exports.getLatestEmailDetails = getLatestEmailDetails;
