import jingrow
from jingrow.query_builder import Not
from jingrow.query_builder.functions import Count
from jingrow.query_builder.terms import QueryBuilder


def check(base_query: QueryBuilder, document_type: str, document_name: str) -> bool | list[str]:
	if document_name:
		return document(base_query, document_type, document_name)
	return documents(base_query, document_type)


def documents(base_query: QueryBuilder, document_type: str) -> list[str]:
	JcloudeRole = jingrow.qb.PageType("Jcloude Role")
	JcloudeRoleResource = jingrow.qb.PageType("Jcloude Role Resource")
	return [
		pg.document_name
		for pg in base_query.inner_join(JcloudeRoleResource)
		.on(
			(JcloudeRoleResource.parent == JcloudeRole.name)
			& (JcloudeRoleResource.document_type == document_type)
			& (Not(JcloudeRoleResource.document_name.isnull()))
		)
		.select(JcloudeRoleResource.document_name)
		.distinct()
		.run(as_dict=True)
	]


def document(base_query: QueryBuilder, document_type: str, document_name: str) -> bool:
	JcloudeRole = jingrow.qb.PageType("Jcloude Role")
	JcloudeRoleResource = jingrow.qb.PageType("Jcloude Role Resource")
	return (
		base_query.inner_join(JcloudeRoleResource)
		.on(
			(JcloudeRoleResource.parent == JcloudeRole.name)
			& (JcloudeRoleResource.document_type == document_type)
			& (JcloudeRoleResource.document_name == document_name)
		)
		.select(Count(JcloudeRole.name).as_("document_count"))
		.run(as_dict=True)
		.pop()
		.get("document_count")
		> 0
	)
