"""
Database router for directing queries to the appropriate database.

The UKSI Browser app uses a separate read-only SQLite database,
while all other apps use the default database.
"""


class UKSIBrowserRouter:
    """
    A router to control all database operations for the uksi_browser app.
    """
    
    route_app_labels = {'uksi_browser'}
    
    def db_for_read(self, model, **hints):
        """
        Attempts to read uksi_browser models go to the 'uksi' database.
        """
        if model._meta.app_label in self.route_app_labels:
            return 'uksi'
        return None
    
    def db_for_write(self, model, **hints):
        """
        Attempts to write uksi_browser models go to the 'uksi' database.
        Note: The UKSI database is read-only, so writes should fail.
        """
        if model._meta.app_label in self.route_app_labels:
            return 'uksi'
        return None
    
    def allow_relation(self, obj1, obj2, **hints):
        """
        Allow relations if both objects are in the uksi_browser app,
        or if neither is in the uksi_browser app.
        """
        if (
            obj1._meta.app_label in self.route_app_labels or
            obj2._meta.app_label in self.route_app_labels
        ):
            return obj1._meta.app_label == obj2._meta.app_label
        return None
    
    def allow_migrate(self, db, app_label, model_name=None, **hints):
        """
        Make sure the uksi_browser app only appears in the 'uksi' database,
        and that other apps don't appear in the 'uksi' database.
        """
        if app_label in self.route_app_labels:
            # uksi_browser models should only migrate to 'uksi' database
            return db == 'uksi'
        # Other apps should not migrate to 'uksi' database
        return db != 'uksi'

