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'
import type { DurableObjectNamespace } from '@cloudflare/workers-types'

/**
 * 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 = async (): Promise<void> => {
  console.log("scheduling store initialization")
  const env = (globalThis as { ENV?: { CACHE_CREATOR?: DurableObjectNamespace } }).ENV
  if (!env?.CACHE_CREATOR) {
    console.warn('CACHE_CREATOR durable object binding not available for store initialization')
    return
  }

  const id = env.CACHE_CREATOR.idFromName('store-init')
  const stub = env.CACHE_CREATOR.get(id)
  try {
    await stub.fetch('https://cache-creator/schedule', { method: 'POST' })
  } catch (error) {
    console.error('Failed to schedule store initialization:', error)
  }
}
