export interface ReportFilterField {
  fieldname: string
  label: string
  fieldtype: string
  options?: any
  default?: any
  reqd?: number
  dashboard_config?: Record<string, any>
}

export interface ReportFilterConfig {
  filters: ReportFilterField[]
  resolveDefaults?: () => Promise<Record<string, any>>
}

const win = window as any
if (!win.jingrow) win.jingrow = {}
if (!win.jingrow.vue_extensions) {
  win.jingrow.vue_extensions = {
    report_filters: {} as Record<string, ReportFilterConfig>,
    registerReportFilters,
    getReportFilters
  }
}

export function registerReportFilters(reportName: string, config: ReportFilterConfig): void {
  win.jingrow.vue_extensions.report_filters[reportName] = config
}

export function getReportFilters(reportName: string): ReportFilterConfig | null {
  return win.jingrow.vue_extensions.report_filters[reportName] || null
}

function loadScript(url: string): Promise<void> {
  return new Promise((resolve, reject) => {
    const script = document.createElement('script')
    script.src = url
    script.onload = () => resolve()
    script.onerror = () => reject(new Error(`Failed to load extension: ${url}`))
    document.head.appendChild(script)
  })
}

const extensionGlob = import.meta.glob('@apps/*/frontend/src/shared/extensions/*.ts')
const localExtensionGlob = import.meta.glob('/src/shared/extensions/*.ts')

let extensionsLoaded = false

async function loadExtensionModules(): Promise<void> {
  if (extensionsLoaded) return
  extensionsLoaded = true

  const allExtensions = { ...extensionGlob, ...localExtensionGlob }
  for (const [path, loader] of Object.entries(allExtensions)) {
    try {
      await loader()
    } catch (err) {
      console.error(`[Extensions] Failed to load extension from ${path}:`, err)
    }
  }
}

export async function loadAppExtensions(): Promise<void> {
  // Load TS extension modules from all apps
  await loadExtensionModules()

  // Load legacy JS extensions via script tags
  const urls: string[] = win.jingrow?.boot?.vue_app_extensions || []
  if (!urls.length) return

  const promises = urls.map(url => loadScript(url))
  await Promise.allSettled(promises)
}
