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

from __future__ import annotations

import json

import jingrow

from jcloude.api.site import protected
from jcloude.guards import role_guard


@jingrow.whitelist(allow_guest=True)
def available_events():
	return jingrow.get_all(
		"Jcloude Webhook Event",
		fields=["name", "description"],
		filters={"enabled": 1},
		order_by="creation desc",
	)


@jingrow.whitelist()
@role_guard.document(document_type=lambda _: "Jcloude Webhook")
def add(endpoint: str, secret: str, events: list[str]):
	pg = jingrow.new_pg("Jcloude Webhook")
	pg.endpoint = endpoint
	pg.secret = secret
	pg.team = jingrow.local.team().name
	for event in events:
		pg.append("events", {"event": event})
	pg.save()


@jingrow.whitelist()
@protected("Jcloude Webhook")
@role_guard.document(document_type=lambda _: "Jcloude Webhook")
def update(name: str, endpoint: str, secret: str, events: list[str]):
	pg = jingrow.get_pg("Jcloude Webhook", name)
	pg.endpoint = endpoint
	pg.secret = secret or pg.secret
	pg.events = []
	for event in events:
		pg.append("events", {"event": event})
	pg.save()


@jingrow.whitelist()
@protected("Jcloude Webhook")
@role_guard.document(document_type=lambda _: "Jcloude Webhook Log")
def attempts(webhook: str):
	pg = jingrow.get_pg("Jcloude Webhook", webhook)
	pg.has_permission("read")

	PressWebhookAttempt = jingrow.qb.PageType("Jcloude Webhook Attempt")
	PressWebhookLog = jingrow.qb.PageType("Jcloude Webhook Log")
	query = (
		jingrow.qb.from_(PressWebhookAttempt)
		.select(
			PressWebhookAttempt.name,
			PressWebhookAttempt.endpoint,
			PressWebhookLog.event,
			PressWebhookAttempt.status,
			PressWebhookAttempt.response_status_code,
			PressWebhookAttempt.timestamp,
		)
		.left_join(PressWebhookLog)
		.on(PressWebhookAttempt.parent == PressWebhookLog.name)
		.where(PressWebhookAttempt.webhook == pg.name)
		.orderby(PressWebhookAttempt.timestamp, order=jingrow.qb.desc)
	)
	return query.run(as_dict=1)


@jingrow.whitelist()
@role_guard.document(document_type=lambda _: "Jcloude Webhook Attempt")
def attempt(name: str):
	pg = jingrow.get_pg("Jcloude Webhook Attempt", name)
	pg.has_permission("read")
	data = pg.as_dict()
	data.request_payload = json.loads(jingrow.get_value("Jcloude Webhook Log", pg.parent, "request_payload"))
	return data
