import { Schema, model } from 'mongoose';
import { ICustomFieldsDoc, ICustomFieldsModel } from './customFields.interface';
import { paginate, toJSON } from '@/shared/utils/plugins';
import { CUSTOM_FIELD_TYPE_VALUES, CUSTOM_FORM_NAME_VALUES } from '@/modules/customFields/customFields.constant';

const customFieldsSchema = new Schema<ICustomFieldsDoc>(
  {
    companyId: {
      type: Schema.Types.ObjectId,
      ref: 'Company',
    },
    formName: {
      type: String,
      enum: CUSTOM_FORM_NAME_VALUES,
      required: true,
    },
    label: {
      type: String,
      required: true,
    },
    key: {
      type: String,
      required: true,
    },
    type: {
      type: String,
      enum: CUSTOM_FIELD_TYPE_VALUES,
      required: true,
    },

    section: {
      type: String,
    },
    placeholder: {
      type: String,
    },
    required: {
      type: Boolean,
      default: false,
    },
    isUOM: {
      type: Boolean,
      default: false,
    },
    sequence: {
      type: Number,
      default: 0,
    },
    isDeleted: {
      type: Boolean,
      default: false,
    },
    options: {
      type: [
        {
          label: String,
          value: String,
          isDeleted: { type: Boolean, default: false },
        },
      ],
      default: [],
      _id: false,
    },
    createdBy: {
      type: Schema.Types.ObjectId,
      ref: 'User',
    },
    updatedBy: {
      type: Schema.Types.ObjectId,
      ref: 'User',
    },
  },
  {
    timestamps: true,
  },
);

// plugins
customFieldsSchema.plugin(toJSON);
customFieldsSchema.plugin(paginate);

export const CustomFields = model<ICustomFieldsDoc, ICustomFieldsModel>(
  'CustomFields',
  customFieldsSchema,
);
