# core/db_router.py
class MultiTenantRouter:
    """
    PROPER router for multi-tenant setup
    Key insight: Keep auth models ALWAYS in master DB
    """

    # Models that ALWAYS go to master DB
    MASTER_ONLY_MODELS = {
        ("auth", "user"),
        ("auth", "group"),
        ("auth", "permission"),
        ("admin", "logentry"),
        ("sessions", "session"),
        ("contenttypes", "contenttype"),
        ("master_admin", "school"),
    }

    SCHOOL_APPS = {
        "school_admin",
        "people",
        "academics",
        "schedules",
        "fee",
        "tasks",
        "announcements",
        "attendance",
        "transport",
        "exam",
        "chat",
        "payslips",
        "stats",
        "activities",
        "teacher",
    }

    def _get_model_key(self, model):
        """Get unique model identifier"""
        return (model._meta.app_label, model._meta.model_name)

    def db_for_read(self, model, **hints):
        """
        Routes reads based on model type
        """
        model_key = self._get_model_key(model)

        # Auth/Admin models → Master DB
        if model_key in self.MASTER_ONLY_MODELS:
            return "default"

        # School apps → School DB
        if model._meta.app_label in self.SCHOOL_APPS:
            return "school"

        # Default for everything else
        return "default"

    def db_for_write(self, model, **hints):
        """
        Routes writes based on model type
        SAME logic as db_for_read for consistency
        """
        return self.db_for_read(model, **hints)

    def allow_relation(self, obj1, obj2, **hints):
        """
        ALLOW cross-database relations between User and school models
        This is KEY for your setup
        """
        # Always allow relations involving User model
        if obj1._meta.model_name == "user" or obj2._meta.model_name == "user":
            return True

        # Both in school apps? Allow
        if (
            obj1._meta.app_label in self.SCHOOL_APPS
            and obj2._meta.app_label in self.SCHOOL_APPS
        ):
            return True

        # Both in master? Allow
        if (
            obj1._meta.app_label not in self.SCHOOL_APPS
            and obj2._meta.app_label not in self.SCHOOL_APPS
        ):
            return True

        # Mixed (except User case handled above) - be careful
        return False

    def allow_migrate(self, db, app_label, model_name=None, **hints):
        """
        Control migrations - VERY IMPORTANT
        """
        model_key = (app_label, model_name) if model_name else None

        # Master-only models → ONLY default DB
        if model_key in self.MASTER_ONLY_MODELS:
            return db == "default"

        # School apps → ONLY school DB
        if app_label in self.SCHOOL_APPS:
            return db == "school"

        # Non-school apps → ONLY default DB
        # AND block them from school DB
        if db == "school":
            return False

        return db == "default"
