import axios from "axios";
import dotenv from "dotenv";
dotenv.config();

const type: any = process.env.NODE_ENV;
const tenant: any = process.env.CLIENT_TENANT_ID;
const teamsWebhookUrl: any = process.env.TEAMS_WEBHOOK_URL;
const errorWebhookUrl: any = process.env.TEAMS_ERROR_WEBHOOK_URL;
const responsibleDev: any = process.env.DEVELOPER;

const customMarkdownMessage = (obj: any) => {
	//check if obj is Json parsable or object is JSON
	if (typeof obj === "string") {
		try {
			obj = JSON.parse(obj);
		} catch (error) {
			return obj;
		}
	} else if (typeof obj != "object") {
		console.log(obj);
		return `Object is not JSON parsable \n ${obj}`;
	}

	const entries = Object.entries(obj).map(([key, value]) => {
		if (Array.isArray(value)) {
			if (value.every((item) => typeof item === "object")) {
				return `**${key}** : ${value
					.map((item) => JSON.stringify(item))
					.join(", \n * ")} \n`;
			} else {
				return `**${key}** : ${value.join(", \n * ")} \n`;
			}
		} else if (typeof value === "object") {
			return `**${key}** : ${JSON.stringify(value)} \n`;
		} else {
			return `**${key}** : ${value}`;
		}
	});

	return `\n * ${entries.join(", \n * ")} \n`;
};

const format_Card_Playload = (
	title: string,
	dataSource: string,
	message: any,
	status: string,
	others: any = {}
) => {
	if (message.response) {
		let response = {
			status: message.response.status,
			statusText: message.response.statusText,
			data: message.response.data,
		};
		message = JSON.stringify(response);
	}

	message = customMarkdownMessage(message);
	console.log(message);

	let base = [
		{
			type: "TextBlock",
			text: `**${title}**`,
			style: "heading",
		},
		{
			type: "TextBlock",
			text: `**Server**: ${type == "development" ? type : tenant}`,
			style: "heading",
		},
		{
			type: "TextBlock",
			text: `**Source**: ${dataSource}`,
		},
		{
			type: "TextBlock",
			text: `**Status**: ${status} ${
				status === "Error" ? "❌" : status === "Warning" ? "⚠️" : "✔️"
			}`,
		},
		{
			type: "TextBlock",
			text: `**Message**: \n ${message}`,
			wrap: true,
		},
		{
			type: "TextBlock",
			text: `**Responsible Party**: ${responsibleDev}`,
			wrap: true,
		},
	];

	if (others) {
		Object.keys(others).forEach((key: any) => {
			base.push({
				type: "TextBlock",
				text: `**${key}**: ${others[key]}`,
				wrap: true,
			});
		});
	}

	return {
		type: "message",
		attachments: [
			{
				contentType: "application/vnd.microsoft.card.adaptive",
				contentUrl: null,
				content: {
					$schema: "http://adaptivecards.io/schemas/adaptive-card.json",
					type: "AdaptiveCard",
					version: "1.2",
					body: [
						...base,
						{
							type: "TextBlock",
							text: "**To**: <at>Perry Pue</at>, <at>Ethan Colin Law Yee Theng</at>",
						},
					],
					msteams: {
						entities: [
							{
								type: "mention",
								text: "<at>Perry Pue</at>",
								mentioned: {
									id: "perry@rajang.com",
									name: "Perry Pue",
								},
							},
							{
								type: "mention",
								text: "<at>Ethan Colin Law Yee Theng</at>",
								mentioned: {
									id: "ethan@rajang.com",
									name: "Ethan Colin Law Yee Theng",
								},
							},
						],
					},
				},
			},
		],
	};
};

export const sendTeamsMessageApi = (
	title: any,
	dataSource: any,
	message: any,
	status: any
) => {
	if (errorWebhookUrl || teamsWebhookUrl) {
		axios
			.post(
				status === "Error" || status === "Warning"
					? errorWebhookUrl
					: teamsWebhookUrl,
				format_Card_Playload(title, dataSource, message, status)
			)
			.then((res) => {
				console.log(title, dataSource);
				console.log(`statusCode: ${res.status}`);
			})
			.catch((error) => {
				console.error(error);
			});
	} else {
		console.log("NO AVAILABLE WEBHOOK URL");
		console.log(title, message);
	}
};
