import { RouteDto } from '@/proxy/routes/models'
import { lazy } from 'react'

// Tüm view bileşenlerini import et (vite özel)
// shared klasörü hariç, çünkü bu bileşenler genellikle başka yerlerde statik import ediliyor
const modules = import.meta.glob(['../views/**/*.tsx', '!../views/shared/**/*.tsx'])

const lazyComponentCache = new Map<string, React.LazyExoticComponent<React.ComponentType<any>>>()

export function loadComponent(componentPath: string) {
  const cleanedPath = componentPath.replace(/^@\//, '')
  const fullPath = `../${cleanedPath}.tsx`

  if (lazyComponentCache.has(fullPath)) {
    return lazyComponentCache.get(fullPath)!
  }

  const loader = modules[fullPath]
  if (!loader) {
    console.error(`Component not found for path: ${fullPath}`)
    throw new Error(`Component not found for path: ${fullPath}`)
  }

  const LazyComponent = lazy(loader as () => Promise<{ default: React.ComponentType<any> }>)
  lazyComponentCache.set(fullPath, LazyComponent)
  return LazyComponent
}

// React Router için uygun bir route tipi
export interface DynamicReactRoute {
  key: string
  path: string
  getComponent: () => React.LazyExoticComponent<React.ComponentType<any>>
  routeType: string
  authority?: string[]
}

// API'den gelen route objesini, React Router için uygun hale getirir
export function mapDynamicRoutes(routes: RouteDto[]): DynamicReactRoute[] {
  return routes.map((route) => ({
    key: route.path,
    path: route.path,
    getComponent: () => loadComponent(route.componentPath),
    routeType: route.routeType,
    authority: route.authority,
  }))
}
