module.exports = function (sequelize, DataTypes) {
  const element_type_defaults = sequelize.define(
    'element_type_defaults',
    {
      id: {
        type: DataTypes.UUID,
        defaultValue: DataTypes.UUIDV4,
        primaryKey: true,
      },
      element_type: {
        type: DataTypes.TEXT,
        allowNull: false,
        unique: true,
        validate: {
          notEmpty: { msg: 'Element type is required' },
          len: {
            args: [1, 100],
            msg: 'Element type must be between 1 and 100 characters',
          },
        },
      },
      name: {
        type: DataTypes.TEXT,
        allowNull: false,
        validate: {
          notEmpty: { msg: 'Name is required' },
          len: {
            args: [1, 255],
            msg: 'Name must be between 1 and 255 characters',
          },
        },
      },
      sort_order: {
        type: DataTypes.INTEGER,
        allowNull: false,
        defaultValue: 0,
      },
      is_active: {
        type: DataTypes.VIRTUAL,
        get() {
          return true;
        },
      },
      default_settings_json: {
        type: DataTypes.TEXT,
        field: 'settings_json',
        allowNull: true,
      },
      importHash: {
        type: DataTypes.STRING(255),
        allowNull: true,
        unique: true,
      },
    },
    {
      timestamps: true,
      paranoid: true,
      freezeTableName: true,
      indexes: [
        { fields: ['element_type'] },
        { fields: ['sort_order'] },
        { fields: ['deletedAt'] },
      ],
    },
  );

  element_type_defaults.associate = (db) => {
    db.element_type_defaults.belongsTo(db.users, {
      as: 'createdBy',
    });

    db.element_type_defaults.belongsTo(db.users, {
      as: 'updatedBy',
    });

    // Add hasMany relationship to project_element_defaults
    if (db.project_element_defaults) {
      db.element_type_defaults.hasMany(db.project_element_defaults, {
        as: 'project_defaults',
        foreignKey: {
          name: 'source_element_id',
        },
        constraints: true,
        onDelete: 'SET NULL',
        onUpdate: 'CASCADE',
      });
    }
  };

  return element_type_defaults;
};
