import jingrow
from jingrow.desk.pagetype.notification_log.notification_log import make_notification_logs


def execute():
	if jingrow.get_all("Email Account", {"auth_method": "OAuth", "connected_user": ["is", "set"]}, limit=1):
		return

	# Setting awaiting password to 1 for email accounts where Oauth is enabled.
	# This is done so that people can resetup their email accounts with connected app mechanism.
	jingrow.db.set_value("Email Account", {"auth_method": "OAuth"}, "awaiting_password", 1)

	message = "Email Accounts with auth method as OAuth have been disabled.\
	Please re-setup your OAuth based email accounts with the connected app mechanism to re-enable them."

	if sysmanagers := get_system_managers():
		make_notification_logs(
			{
				"type": "Alert",
				"subject": jingrow._(message),
			},
			sysmanagers,
		)


def get_system_managers():
	user_pagetype = jingrow.qb.PageType("User").as_("user")
	user_role_pagetype = jingrow.qb.PageType("Has Role").as_("user_role")
	return (
		jingrow.qb.from_(user_pagetype)
		.from_(user_role_pagetype)
		.select(user_pagetype.email)
		.where(user_role_pagetype.role == "System Manager")
		.where(user_pagetype.enabled == 1)
		.where(user_role_pagetype.parent == user_pagetype.name)
	).run(pluck=True)
