module.exports = function (sequelize, DataTypes) {
  const project_memberships = sequelize.define(
    'project_memberships',
    {
      id: {
        type: DataTypes.UUID,
        defaultValue: DataTypes.UUIDV4,
        primaryKey: true,
      },

      access_level: {
        type: DataTypes.ENUM,
        allowNull: false,
        defaultValue: 'viewer',

        values: ['owner', 'editor', 'reviewer', 'viewer'],
      },

      is_active: {
        type: DataTypes.BOOLEAN,

        allowNull: false,
        defaultValue: false,
      },

      invited_at: {
        type: DataTypes.DATE,
      },

      accepted_at: {
        type: DataTypes.DATE,
      },

      importHash: {
        type: DataTypes.STRING(255),
        allowNull: true,
        unique: true,
      },
    },
    {
      timestamps: true,
      paranoid: true,
      freezeTableName: true,
      indexes: [
        { fields: ['projectId'] },
        { fields: ['userId'] },
        { fields: ['projectId', 'userId'], unique: true },
        { fields: ['is_active'] },
        { fields: ['deletedAt'] },
      ],
    },
  );

  project_memberships.associate = (db) => {
    /// loop through entities and it's fields, and if ref === current e[name] and create relation has many on parent entity

    //end loop

    db.project_memberships.belongsTo(db.projects, {
      as: 'project',
      foreignKey: {
        name: 'projectId',
      },
      constraints: true,
      onDelete: 'CASCADE',
      onUpdate: 'CASCADE',
    });

    db.project_memberships.belongsTo(db.users, {
      as: 'user',
      foreignKey: {
        name: 'userId',
      },
      constraints: true,
      onDelete: 'CASCADE',
      onUpdate: 'CASCADE',
    });

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

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

  return project_memberships;
};
