# Copyright (c) 2022, Frappe and contributors
# For license information, please see license.txt

from __future__ import annotations

import json

import jingrow

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


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


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


@jingrow.whitelist()
@protected("Press Webhook")
@role_guard.document(document_type=lambda _: "Press Webhook")
def update(name: str, endpoint: str, secret: str, events: list[str]):
	pg = frappe.get_pg("Press 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("Press Webhook")
@role_guard.document(document_type=lambda _: "Press Webhook Log")
def attempts(webhook: str):
	pg = frappe.get_pg("Press Webhook", webhook)
	pg.has_permission("read")

	PressWebhookAttempt = frappe.qb.DocType("Press Webhook Attempt")
	PressWebhookLog = frappe.qb.DocType("Press Webhook Log")
	query = (
		frappe.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=frappe.qb.desc)
	)
	return query.run(as_dict=1)


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