import { Router } from 'express';
import { DataSource } from 'typeorm';
import {
  SystemSetting,
  PlanSetting,
  TenantSetting,
  UserPreference,
} from './entities';
import {
  SystemSettingsService,
  TenantSettingsService,
  UserPreferencesService,
} from './services';
import {
  SystemSettingsController,
  TenantSettingsController,
  UserPreferencesController,
} from './controllers';

/**
 * Creates and configures the settings routes
 *
 * Routes:
 * - /api/v1/settings/system/*  - System settings (global configuration)
 * - /api/v1/settings/tenant/*  - Tenant settings (organization overrides)
 * - /api/v1/settings/user/*    - User preferences (personal settings)
 *
 * @param dataSource - TypeORM DataSource instance
 * @returns Configured Express Router
 */
export function createSettingsRoutes(dataSource: DataSource): Router {
  const router = Router();

  // Initialize repositories
  const systemSettingRepository = dataSource.getRepository(SystemSetting);
  const planSettingRepository = dataSource.getRepository(PlanSetting);
  const tenantSettingRepository = dataSource.getRepository(TenantSetting);
  const userPreferenceRepository = dataSource.getRepository(UserPreference);

  // Initialize services
  const systemSettingsService = new SystemSettingsService(systemSettingRepository);
  const tenantSettingsService = new TenantSettingsService(
    tenantSettingRepository,
    systemSettingRepository,
    planSettingRepository
  );
  const userPreferencesService = new UserPreferencesService(userPreferenceRepository);

  // Initialize controllers
  const systemSettingsController = new SystemSettingsController(systemSettingsService);
  const tenantSettingsController = new TenantSettingsController(tenantSettingsService);
  const userPreferencesController = new UserPreferencesController(userPreferencesService);

  // Mount routes
  router.use('/system', systemSettingsController.router);
  router.use('/tenant', tenantSettingsController.router);
  router.use('/user', userPreferencesController.router);

  return router;
}

export default createSettingsRoutes;
