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

import jingrow
from jingrow.model.page import Page


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

		site: DF.Link
		token: DF.Data
	# end: auto-generated types

	@staticmethod
	def generate(site: str) -> str:
		record = jingrow.get_pg(
			{
				"pagetype": "Site Access Token",
				"site": site,
				"token": jingrow.generate_hash(length=32),
			}
		).insert(ignore_permissions=True)
		return f"{record.name}:{record.token}"


def cleanup_expired_access_tokens():
	# cleanup expired tokens
	jingrow.db.sql(
		"""
		DELETE FROM `tabSite Access Token`
		WHERE TIMESTAMPDIFF(MINUTE, creation, NOW()) > 30
		"""
	)
	jingrow.db.commit()
