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

import jingrow
from jingrow.model.page import Page

from jcloud.api.client import dashboard_whitelist


class JcloudRolePermission(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

		release_group: DF.Link | None
		role: DF.Link
		server: DF.Link | None
		site: DF.Link | None
		team: DF.Link
	# end: auto-generated types

	dashboard_fields = ("site", "release_group", "server", "role")

	def before_insert(self):
		is_admin_role = jingrow.db.get_value("Jcloud Role", self.role, "admin_access")
		if (
			not jingrow.local.system_user()
			and jingrow.session.user != jingrow.db.get_value("Team", self.team, "user")
			and not is_admin_role
		):
			jingrow.throw("Only the team owner or admin can create role permissions")

		if jingrow.db.exists(
			"Jcloud Role Permission",
			{
				"role": self.role,
				"team": self.team,
				"site": self.site,
				"release_group": self.release_group,
				"server": self.server,
			},
		):
			jingrow.throw("Role Permission already exists")

	@dashboard_whitelist()
	def delete(self):
		is_admin_role = jingrow.db.get_value("Jcloud Role", self.role, "admin_access")
		if (
			not jingrow.local.system_user()
			and jingrow.session.user != jingrow.get_cached_value("Team", self.team, "user")
			and not is_admin_role
		):
			jingrow.throw("Only the team owner or admin can delete this role permission")

		super().delete()
