# Copyright (c) 2023, Jingrow and Contributors
# See license.txt

import jingrow
from jingrow.tests.utils import FrappeTestCase

from jcloude.jcloude.pagetype.jcloude_user_permission.jcloude_user_permission import (
	has_user_permission,
)
from jcloude.jcloude.pagetype.site.test_site import create_test_site
from jcloude.jcloude.pagetype.team.test_team import create_test_team


class TestPressUserPermission(FrappeTestCase):
	def setUp(self):
		super().setUp()

		self.team = create_test_team()
		self.site = create_test_site(subdomain="testpermsite")

	def tearDown(self):
		jingrow.set_user("Administrator")
		jingrow.db.rollback()

	def test_jcloude_user_permission(self):
		self.assertFalse(has_user_permission("Site", self.site.name, "jcloude.api.site.login"))

		jingrow.get_pg(
			pagetype="Jcloude User Permission",
			type="User",
			user=jingrow.session.user,
			document_type="Site",
			document_name=self.site.name,
			action="jcloude.api.site.login",
		).insert(ignore_permissions=True)

		self.assertTrue(has_user_permission("Site", self.site.name, "jcloude.api.site.login"))
		self.assertFalse(has_user_permission("Site", self.site.name, "jcloude.api.site.migrate"))

	def test_jcloude_group_permission(self):
		group = jingrow.get_pg(pagetype="Jcloude Permission Group", team=self.team.name, title="Test Group")
		group.append("users", {"user": jingrow.session.user})
		group.insert(ignore_permissions=True)

		jingrow.get_pg(
			pagetype="Jcloude User Permission",
			type="Group",
			group=group.name,
			document_type="Site",
			document_name=self.site.name,
			action="jcloude.api.site.overview",
		).insert(ignore_permissions=True)

		self.assertTrue(
			has_user_permission("Site", self.site.name, "jcloude.api.site.overview", groups=[group.name])
		)
		self.assertFalse(
			has_user_permission("Site", self.site.name, "jcloude.api.site.migrate", groups=[group.name])
		)

	def test_jcloude_config_permission(self):
		perms = {
			"global": {
				"Site": {"*": "jcloude.api.site.login"},
			},
			"restricted": {"Site": {"test.jingrow.dev": "jcloude.api.site.migrate"}},
		}
		jingrow.get_pg(
			pagetype="Jcloude User Permission",
			type="Config",
			config=jingrow.as_json(perms),
			user=jingrow.session.user,
		).insert(ignore_permissions=True)

		self.assertTrue(has_user_permission("Site", self.site.name, "jcloude.api.site.login"))
		self.assertFalse(has_user_permission("Site", "sometest.jingrow.dev", "jcloude.api.site.restore"))
		self.assertFalse(has_user_permission("Site", "test.jingrow.dev", "jcloude.api.site.migrate"))
		self.assertTrue(has_user_permission("Site", "test.jingrow.dev", "jcloude.api.site.login"))
