# acl/repository/factory.py
from sqlalchemy.orm import Session
from sqlalchemy import select

from acl.models.datasource_mapping import EntityDatasourceMapping
from acl.repository.interface import DynamicAclRepository
from acl.repository.jpa_acl_repository import JpaAclRepositoryImpl


class AclRepositoryFactory:
    """
    Decides which underlying ACL repository implementation to use
    """

    def __init__(self, db: Session, jpa_repo: DynamicAclRepository | None = None):
        self.db = db
        self.jpa_repo = jpa_repo or JpaAclRepositoryImpl()

    def get_datasource_for_entity(self, entity_type: str) -> str:
        datasource = self.db.execute(
            select(EntityDatasourceMapping.datasource).where(
                EntityDatasourceMapping.entity == entity_type
            )
        ).scalar_one_or_none()

        return datasource or "SQL"

    def get_repository(self, entity_type: str) -> DynamicAclRepository:
        datasource = self.get_datasource_for_entity(entity_type)
        if datasource == "SQL":
            return self.jpa_repo
        return self.jpa_repo  # extend here for Cassandra, Mongo, etc.
