module.exports = function (sequelize, DataTypes) {
  const project_element_defaults = sequelize.define(
    'project_element_defaults',
    {
      id: {
        type: DataTypes.UUID,
        defaultValue: DataTypes.UUIDV4,
        primaryKey: true,
      },
      element_type: {
        // TEXT for flexibility - matches element_type_defaults and page_elements
        type: DataTypes.TEXT,
        allowNull: false,
        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,
        validate: {
          len: { args: [0, 255], msg: 'Name must be at most 255 characters' },
        },
      },
      sort_order: {
        type: DataTypes.INTEGER,
        allowNull: false,
        defaultValue: 0,
      },
      settings_json: {
        type: DataTypes.TEXT,
        allowNull: true,
      },
      source_element_id: {
        // Optional FK - tracks which global default this was snapshotted from
        // SET NULL on global delete to preserve project overrides
        type: DataTypes.UUID,
        allowNull: true,
      },
      snapshot_version: {
        // Increments when resetting from global - enables "check for updates" feature
        type: DataTypes.INTEGER,
        allowNull: false,
        defaultValue: 1,
      },
      importHash: {
        type: DataTypes.STRING(255),
        allowNull: true,
        unique: true,
      },
    },
    {
      timestamps: true,
      paranoid: true,
      freezeTableName: true,
      indexes: [
        { fields: ['projectId'] },
        { fields: ['projectId', 'element_type'], unique: true },
        { fields: ['element_type'] },
        { fields: ['source_element_id'] },
        { fields: ['deletedAt'] },
      ],
    },
  );

  project_element_defaults.associate = (db) => {
    db.project_element_defaults.belongsTo(db.projects, {
      as: 'project',
      foreignKey: {
        name: 'projectId',
        allowNull: false,
      },
      constraints: true,
      onDelete: 'CASCADE',
      onUpdate: 'CASCADE',
    });

    db.project_element_defaults.belongsTo(db.element_type_defaults, {
      as: 'source_element',
      foreignKey: {
        name: 'source_element_id',
      },
      constraints: true,
      onDelete: 'SET NULL',
      onUpdate: 'CASCADE',
    });

    db.project_element_defaults.belongsTo(db.users, {
      as: 'createdBy',
    });

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

  return project_element_defaults;
};
