"""
Tenant-aware database router for schema separation.
Routes database queries to tenant-specific schemas.
"""
import threading
from django.conf import settings
from django.db import connection
from .models import Tenant

# Thread-local storage for current tenant context
_local = threading.local()

def set_tenant(tenant):
    """Set the current tenant for this thread."""
    if tenant:
        _local.tenant = tenant
        # Set PostgreSQL schema search path to tenant schema
        schema_name = f"tenant_{tenant.tenant_code}"
        with connection.cursor() as cursor:
            # Quote schema name to handle uppercase characters
            cursor.execute(f'SET search_path TO "{schema_name}", public')
    else:
        _local.tenant = None
        # Reset to default public schema
        with connection.cursor() as cursor:
            cursor.execute("SET search_path TO public")

def get_current_tenant():
    """Get the current tenant for this thread."""
    return getattr(_local, 'tenant', None)

def get_tenant_schema_name(tenant_code=None):
    """Get the schema name for a tenant."""
    if not tenant_code:
        tenant = get_current_tenant()
        if not tenant:
            return 'public'
        tenant_code = tenant.tenant_code
    return f"tenant_{tenant_code}"

class TenantDatabaseRouter:
    """
    Database router that routes queries to tenant-specific schemas.
    """
    
    def db_for_read(self, model, **hints):
        """Suggest the database to read from."""
        if self._is_tenant_model(model):
            return self._get_tenant_database()
        return None
    
    def db_for_write(self, model, **hints):
        """Suggest the database to write to."""
        if self._is_tenant_model(model):
            return self._get_tenant_database()
        return None
    
    def allow_migrate(self, db, app_label, model_name=None, **hints):
        """Determine if migration should run on this database."""
        # Allow tenant app migrations on all databases
        if app_label == 'tenants':
            return True
            
        # Allow tenant-aware model migrations
        if self._is_tenant_app(app_label):
            return True
            
        return None
    
    def _is_tenant_model(self, model):
        """Check if model should be tenant-aware."""
        # These models should be isolated per tenant
        tenant_apps = ['customers', 'inventory', 'sales', 'orders', 'suppliers', 'hr', 'billing']
        return model._meta.app_label in tenant_apps
    
    def _is_tenant_app(self, app_label):
        """Check if app contains tenant-aware models."""
        tenant_apps = ['customers', 'inventory', 'sales', 'orders', 'suppliers', 'hr', 'billing']
        return app_label in tenant_apps
    
    def _get_tenant_database(self):
        """Get the database for current tenant (always default for schema approach)."""
        return 'default'