import roleManager from '@/src/lib/roles-manager'
import { computeConstants } from '@/src/lib/const-store'
import { initializeProducts } from '@/src/stores/product-store'
import { initializeProductTagStore } from '@/src/stores/product-tag-store'
import { initializeSlotStore } from '@/src/stores/slot-store'
import { initializeBannerStore } from '@/src/stores/banner-store'
import { createAllCacheFiles } from '@/src/lib/cloud_cache'

const STORE_INIT_DELAY_MS = 3 * 60 * 1000
let storeInitializationTimeout: NodeJS.Timeout | null = null

/**
 * Initialize all application stores
 * This function handles initialization of:
 * - Role Manager (fetches and caches all roles)
 * - Const Store (syncs constants from DB to Redis)
 * - Product Store (caches all products in Redis)
 * - Product Tag Store (caches all product tags in Redis)
 * - Slot Store (caches all delivery slots with products in Redis)
 * - Banner Store (caches all banners in Redis)
 */
export const initializeAllStores = async (): Promise<void> => {
  try {
    console.log('Starting application stores initialization...');

    await Promise.all([
      roleManager.fetchRoles(),
      computeConstants(),
      initializeProducts(),
      initializeProductTagStore(),
      initializeSlotStore(),
      initializeBannerStore(),
    ]);

    console.log('All application stores initialized successfully');

    // Regenerate all cache files (fire-and-forget)
    createAllCacheFiles().catch(error => {
      console.error('Failed to regenerate cache files during store initialization:', error)
    })
  } catch (error) {
    console.error('Application stores initialization failed:', error);
    throw error;
  }
};

export const scheduleStoreInitialization = (): void => {
  if (storeInitializationTimeout) {
    clearTimeout(storeInitializationTimeout)
    storeInitializationTimeout = null
  }

  storeInitializationTimeout = setTimeout(() => {
    storeInitializationTimeout = null
    initializeAllStores().catch(error => {
      console.error('Scheduled store initialization failed:', error)
    })
  }, STORE_INIT_DELAY_MS)
}
