# Copyright (c) 2024, JINGROW
# For license information, please see license.txt

from __future__ import annotations

import jingrow
from jingrow.model.page import Page


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

		document_name: DF.DynamicLink
		document_type: DF.Link
		from_team: DF.Link
		key: DF.Data | None
		reason: DF.LongText | None
		to_team: DF.Link
		transfer_completed: DF.Check
	# end: auto-generated types

	def validate(self):
		team = jingrow.get_pg(self.document_type, self.document_name).team
		if team != self.from_team:
			jingrow.throw(f"The owner of {self.document_type} is not {self.from_team}")

	def on_update(self):
		if self.document_type == "Site" and self.transfer_completed:
			notify_email = jingrow.get_value("Team", self.to_team, "user")
			jingrow.db.set_value(
				"Site", self.document_name, {"team": self.to_team, "notify_email": notify_email}
			)
			jingrow.db.set_value(
				"Subscription",
				{"document_name": self.document_name},
				"team",
				self.to_team,
			)
			jingrow.db.set_value("Site Domain", {"site": self.document_name}, "team", self.to_team)
			tls_certificates = jingrow.get_all(
				"Site Domain",
				filters={"site": self.document_name},
				fields=["tls_certificate"],
				pluck="tls_certificate",
			)
			jingrow.db.set_value("TLS Certificate", {"name": ["in", tls_certificates]}, "team", self.to_team)

		if self.document_type == "Release Group" and self.transfer_completed:
			jingrow.db.set_value("Release Group", self.document_name, "team", self.to_team)
