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

import jingrow
from jingrow.model.page import Page


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

		enabled: DF.Check
		site: DF.Link
		user: DF.Data
	# end: auto-generated types

	def login_to_site(self):
		"""Login to the site."""
		if not self.enabled:
			jingrow.throw("User is disabled")

		site = jingrow.get_pg("Site", self.site)
		return site.login_as_user(self.user)


def create_user_for_product_site(site, data):
	analytics = data["analytics"]
	users_data = analytics.get("users", [])
	for user_data in users_data:
		user_mail = user_data.get("email")
		enabled = user_data.get("enabled")
		if jingrow.db.exists("Site User", {"site": site, "user": user_mail}):
			user = jingrow.db.get_value(
				"Site User", {"site": site, "user": user_mail}, ["name", "enabled"], as_dict=True
			)
			if user.enabled != enabled:
				jingrow.db.set_value("Site User", user.name, "enabled", enabled)
		else:
			user = jingrow.get_pg(
				{"pagetype": "Site User", "site": site, "user": user_mail, "enabled": enabled}
			)
			user.insert(ignore_permissions=True)
