import type {
  VbenFormSchema as FormSchema,
  VbenFormProps,
} from '@vben-core/form-ui';

import type { ComponentType } from './component';

import { setupVbenForm, useVbenForm as useForm, z } from '@vben-core/form-ui';
import { $t } from '@vben/locales';

import { initComponentAdapter } from './component';

let initialized = false;

function initSetupVbenForm() {
  if (initialized) {
    return;
  }

  initComponentAdapter();
  setupVbenForm<ComponentType>({
    config: {
      modelPropNameMap: {
        Upload: 'fileList',
        CheckboxGroup: 'model-value',
      },
    },
    defineRules: {
      required: (value, _params, ctx) => {
        if (value === undefined || value === null || value.length === 0) {
          return $t('ui.formRules.required', [ctx.label]);
        }
        return true;
      },
      selectRequired: (value, _params, ctx) => {
        if (value === undefined || value === null) {
          return $t('ui.formRules.selectRequired', [ctx.label]);
        }
        return true;
      },
    },
  });
  initialized = true;
}

const useVbenForm = ((...args: Parameters<typeof useForm<ComponentType>>) => {
  initSetupVbenForm();
  return useForm<ComponentType>(...args);
}) as typeof useForm<ComponentType>;

export { initSetupVbenForm, useVbenForm, z };

export type VbenFormSchema = FormSchema<ComponentType>;
export type { VbenFormProps };
