import type { FieldWatchPlugin } from '@/core/plugins/fieldPlugin'
import { api } from '@/shared/api/common'

const plugins: FieldWatchPlugin[] = [
  {
    fieldname: 'pg_type',
    handler: async (ctx) => {
      if (!ctx.value) return

      try {
        const result = await api.call('jingrow.handler.run_pg_method', {
          pgs: JSON.stringify({
            pagetype: 'Customize Form',
            name: 'Customize Form',
            pg_type: ctx.value
          }),
          method: 'fetch_to_customize'
        })

        const updatedDoc = result?.pgs?.[0]
        if (updatedDoc) {
          Object.keys(updatedDoc).forEach(key => {
            ctx.record[key] = updatedDoc[key]
          })
          // Switch to "Form" tab after loading
          window.dispatchEvent(new CustomEvent('switch-active-tab', { detail: 'form_tab' }))
        }
      } catch (err: any) {
        console.error('[Customize Form] fetch_to_customize failed:', err)
      }
    }
  }
]

export default plugins
