# Copyright (c) 2019, JINGROW
# For license information, please see license.txt

from __future__ import annotations

import json

import jingrow
from jingrow.model import default_fields
from jingrow.model.page import Page


def create_webhook_event(event: str, payload: dict | Page, team: str) -> bool:
	try:
		# Check if team has configured webhook against this event
		JcloudWebhookSelectedEvent = jingrow.qb.PageType("Jcloud Webhook Selected Event")
		JcloudWebhook = jingrow.qb.PageType("Jcloud Webhook")

		query = (
			jingrow.qb.from_(JcloudWebhookSelectedEvent)
			.select(jingrow.query_builder.functions.Count(JcloudWebhookSelectedEvent.name).as_("count"))
			.left_join(JcloudWebhook)
			.on(JcloudWebhookSelectedEvent.parent == JcloudWebhook.name)
			.where(JcloudWebhookSelectedEvent.event == event)
			.where(JcloudWebhook.team == team)
			.where(JcloudWebhook.enabled == 1)
		)

		result = query.run(as_dict=True)
		is_any_webhook_enabled = result and result[0].get("count") > 0
		if is_any_webhook_enabled:
			# prepare request payload
			data = {}
			if isinstance(payload, dict):
				data = jingrow._dict(payload)
			elif isinstance(payload, Page):
				data = _process_document_payload(payload)
			else:
				jingrow.throw("Invalid data type")

			request_payload = json.dumps(
				{
					"event": event,
					"data": data,
				},
				default=str,
				indent=4,
			)

			# create webhook log
			jingrow.get_pg(
				{
					"pagetype": "Jcloud Webhook Log",
					"status": "Pending",
					"event": event,
					"team": team,
					"request_payload": request_payload,
				}
			).insert(ignore_permissions=True)
		return True
	except Exception:
		jingrow.log_error("failed to queue webhook event")
		return False


def _process_document_payload(payload: Page):
	# convert payload to dict
	# send fields mentioned in dashboard_fields, as other fields can have sensitive information
	fields = list(default_fields)
	if hasattr(payload, "dashboard_fields"):
		fields += payload.dashboard_fields
	_pg = jingrow._dict()
	for fieldname in fields:
		_pg[fieldname] = payload.get(fieldname)

	return _pg
