import jingrow
from jingrow.model.naming import is_autoincremented

possible_log_types = (
	"Version",
	"Error Log",
	"Scheduled Job Log",
	"Event Sync Log",
	"Event Update Log",
	"Access Log",
	"View Log",
	"System Log",
	"Energy Point Log",
	"Notification Log",
	"Email Queue",
	"PageShare",
	"Page Follow",
	"Console Log",
)


def execute():
	"""Few pagetypes had int PKs even though schema didn't mention them, this requires detecting it
	at runtime which is prone to bugs and adds unnecessary overhead.

	This patch converts them back to varchar.
	"""
	for pagetype in possible_log_types:
		if (
			jingrow.db.exists("PageType", pagetype)
			and _is_implicit_int_pk(pagetype)
			and not is_autoincremented(pagetype)
		):
			jingrow.db.change_column_type(
				pagetype,
				"name",
				type=f"varchar({jingrow.db.VARCHAR_LEN})",
				nullable=True,
			)


def _is_implicit_int_pk(pagetype: str) -> bool:
	query = f"""select data_type FROM information_schema.columns where column_name = 'name' and table_name = 'tab{pagetype}'"""
	values = ()
	if jingrow.db.db_type == "mariadb":
		query += " and table_schema = %s"
		values = (jingrow.db.cur_db_name,)

	col_type = jingrow.db.sql(query, values)
	return bool(col_type and col_type[0][0] == "bigint")
