import { logger } from '../../debugConfig';
import { storageService, StorageKeys } from '../auth/localStorageService';

export class DatabaseNameService {
  static readonly CC_USERS = 'cc.users';
  static readonly CC_SCHOOLS = 'cc.institutes';

  private static remember(key: StorageKeys, value?: string | null) {
    if (!value) {
      return;
    }
    storageService.set(key, value);
  }

  private static recall<T extends StorageKeys>(key: T): string | null {
    return storageService.get(key);
  }
  
  private static sanitizeComponent(component: string, fallback = 'user'): string {
    const cleaned = (component || fallback)
      .toLowerCase()
      .replace(/[^a-z0-9]+/g, '');
    return cleaned || fallback;
  }

  static getUserPrivateDB(userType: string, identifier: string): string {
    const role = this.sanitizeComponent(userType || 'standard', 'standard');
    const idComponent = this.sanitizeComponent(identifier, 'user');
    const dbName = `${this.CC_USERS}.${role}.${idComponent}`;
    logger.debug('database-name-service', '📥 Generating user private DB name', {
      userType,
      identifier,
      dbName
    });
    return dbName;
  }
  
  static getSchoolPrivateDB(schoolId: string): string {
    const dbName = `${this.CC_SCHOOLS}.${schoolId}`;
    logger.debug('database-name-service', '📥 Generating school private DB name', {
      schoolId,
      dbName
    });
    return dbName;
  }
  
  static getDevelopmentSchoolDB(): string {
    const stored = this.recall(StorageKeys.NEO4J_WORKER_DB);
    if (stored && stored !== `${this.CC_SCHOOLS}.development.default`) {
      logger.debug('database-name-service', '📥 Using stored school DB name', {
        dbName: stored
      });
      return stored;
    }

    if (stored) {
      logger.warn('database-name-service', '⚠️ Ignoring legacy stored school DB name', {
        dbName: stored
      });
    } else {
      logger.warn('database-name-service', '⚠️ No stored school DB name available; returning empty string');
    }
    return '';
  }

  static rememberDatabaseNames({ userDbName, schoolDbName }: { userDbName?: string | null; schoolDbName?: string | null }) {
    this.remember(StorageKeys.NEO4J_USER_DB, userDbName ?? null);
    this.remember(StorageKeys.NEO4J_WORKER_DB, schoolDbName ?? null);
    logger.debug('database-name-service', '💾 Remembered database names', {
      userDbName,
      schoolDbName
    });
  }

  static getStoredUserDatabase(): string | null {
    return this.recall(StorageKeys.NEO4J_USER_DB);
  }

  static getStoredSchoolDatabase(): string | null {
    return this.recall(StorageKeys.NEO4J_WORKER_DB);
  }
  
  static getContextDatabase(context: string, userType: string, identifier: string): string {
    logger.debug('database-name-service', '📥 Resolving context database', {
      context,
      userType,
      identifier
    });

    // For school-related contexts, use the schools database
    if (['school', 'department', 'class'].includes(context)) {
      logger.debug('database-name-service', '✅ Using schools database for context', {
        context,
        dbName: this.CC_SCHOOLS
      });
      return this.CC_SCHOOLS;
    }
    
    // For user-specific contexts, use their private database
    const userDb = this.getUserPrivateDB(userType, identifier);
    logger.debug('database-name-service', '✅ Using user private database for context', {
      context,
      dbName: userDb
    });
    return userDb;
  }
} 
