# Copyright (c) 2022, JINGROW
# For license information, please see license.txt
from __future__ import annotations

import jingrow
from jingrow.model.page import Page

from jcloud.utils import log_error
from jcloud.utils.billing import get_razorpay_client


class RazorpayWebhookLog(Page):
	# begin: auto-generated types
	# This code is auto-generated. Do not modify anything in this block.

	from typing import TYPE_CHECKING

	if TYPE_CHECKING:
		from jingrow.types import DF

		event: DF.Data | None
		payload: DF.Code | None
		payment_id: DF.Data | None
	# end: auto-generated types

	def after_insert(self):
		payment_record = jingrow.get_pg("Razorpay Payment Record", {"order_id": self.name})

		if self.event in ("order.paid", "payment.captured") and payment_record.status != "Captured":
			payment_record.update({"payment_id": self.payment_id, "status": "Captured"})
			payment_record.save(ignore_permissions=True)


@jingrow.whitelist(allow_guest=True)
def razorpay_authorized_payment_handler():
	client = get_razorpay_client()
	form_dict = jingrow.local.form_dict

	payment_id = None
	try:
		payload = jingrow.request.get_data()
		signature = jingrow.get_request_header("X-Razorpay-Signature")
		webhook_secret = jingrow.db.get_single_value("Jcloud Settings", "razorpay_webhook_secret")
		entity_data = form_dict["payload"]["payment"]["entity"]

		client.utility.verify_webhook_signature(payload.decode(), signature, webhook_secret)
		if entity_data["status"] != "authorized":
			raise Exception("invalid payment status received")
		payment_id = entity_data.get("id")
		order_id = entity_data.get("order_id", "")
		amount = entity_data.get("amount")
		notes = entity_data.get("notes")

		if not order_id:
			return

		razorpay_payment_record = jingrow.db.exists("Razorpay Payment Record", {"order_id": order_id})
		if not razorpay_payment_record:
			# Don't log error if its not JingrowCloud order
			# Example of valid notes
			# "notes": {
			# 	"Description": "Order for Jingrow Prepaid Credits",
			# 	"Team (Jingrow ID)": "test@example.com"
			#   "gst": 245
			# },

			if notes and notes.get("description"):
				log_error(
					"Razorpay payment record for given order does not exist",
					order_id=order_id,
				)
			return

		# Only capture payment, if the status of order id is pending
		if jingrow.db.get_value("Razorpay Payment Record", razorpay_payment_record, "status") != "Pending":
			return

		# Capture the authorized payment
		client.payment.capture(payment_id, amount)
	except Exception as e:
		error_message = str(e)
		if (
			"payment has already been captured" in error_message
			or "the order is already paid" in error_message
			or "id provided does not exist" in error_message
		):
			return
		log_error(
			title="Razorpay Authorized Payment Webhook Handler",
			payment_id=payment_id,
		)
		raise Exception from e


@jingrow.whitelist(allow_guest=True)
def razorpay_webhook_handler():
	client = get_razorpay_client()
	current_user = jingrow.session.user
	form_dict = jingrow.local.form_dict

	try:
		payload = jingrow.request.get_data()
		signature = jingrow.get_request_header("X-Razorpay-Signature")
		webhook_secret = jingrow.db.get_single_value("Jcloud Settings", "razorpay_webhook_secret")

		client.utility.verify_webhook_signature(payload.decode(), signature, webhook_secret)

		# set user to Administrator, to not have to do ignore_permissions everywhere
		jingrow.set_user("Administrator")

		entity_data = form_dict["payload"]["payment"]["entity"]
		razorpay_order_id = entity_data.get("order_id")

		if not razorpay_order_id:
			return

		razorpay_payment_record = jingrow.db.exists("Razorpay Payment Record", {"order_id": razorpay_order_id})

		notes = form_dict["payload"]["payment"]["entity"]["notes"]
		if not razorpay_payment_record:
			# Don't log error if its not JingrowCloud order
			# Example of valid notes
			# "notes": {
			# 	"Description": "Order for Jingrow Prepaid Credits",
			# 	"Team (Jingrow ID)": "test@example.com",
			# 	"gst": 245
			# },

			if notes and notes.get("description"):
				log_error(
					"Razorpay payment record for given order does not exist",
					order_id=razorpay_order_id,
				)
			return

		jingrow.get_pg(
			{
				"pagetype": "Razorpay Webhook Log",
				"payload": jingrow.as_json(form_dict),
				"event": form_dict.get("event"),
				"payment_id": form_dict["payload"]["payment"]["entity"]["id"],
				"name": razorpay_order_id,
			}
		).insert(ignore_if_duplicate=True)

	except Exception as e:
		jingrow.db.rollback()
		log_error(
			title="Razorpay Webhook Handler",
			payment_id=form_dict["payload"]["payment"]["entity"]["id"],
		)
		jingrow.set_user(current_user)
		raise Exception from e
