import jingrow

from jcloud.api.client import dashboard_whitelist
from jcloud.utils import get_full_chain_cert_of_domain, get_minified_script, get_minified_script_2, log_error


@jingrow.whitelist(allow_guest=True)
def script():
	return get_minified_script()


@jingrow.whitelist(allow_guest=True)
def script_2():
	return get_minified_script_2()


@jingrow.whitelist(allow_guest=True)
def handle_suspended_site_redirection():
	from jcloud.saas.pagetype.product_trial_request.product_trial_request import (
		get_app_trial_page_url,
	)

	jingrow.local.response["type"] = "redirect"
	jingrow.local.response["location"] = get_app_trial_page_url() or "/dashboard"


@dashboard_whitelist()
def download_ssl_cert(domain: str):
	if (
		not (domain.endswith("jingrow.cloud") or domain.endswith("jingrow.com"))
		and not jingrow.conf.developer_mode
	):
		jingrow.throw("Invalid domain provided")

	try:
		return get_full_chain_cert_of_domain(domain)
	except Exception as e:
		log_error("Error downloading SSL certificate", data=e)
		jingrow.throw("Failed to download SSL certificate. Please try again later.")
