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

      name: {
        type: DataTypes.TEXT,
        validate: {
          len: {
            args: [0, 255],
            msg: 'Asset name must be at most 255 characters',
          },
        },
      },

      asset_type: {
        type: DataTypes.ENUM,
        allowNull: false,

        values: ['image', 'video', 'audio', 'file'],
      },

      type: {
        type: DataTypes.ENUM,
        allowNull: false,
        defaultValue: 'general',

        values: [
          'icon',

          'background_image',

          'audio',

          'video',

          'transition',

          'logo',

          'favicon',

          'document',

          'general',
        ],
      },

      cdn_url: {
        type: DataTypes.TEXT,
      },

      storage_key: {
        type: DataTypes.TEXT,
      },

      mime_type: {
        type: DataTypes.TEXT,
        validate: {
          is: {
            args: /^[a-z0-9]+\/[a-z0-9.+-]+$/i,
            msg: 'Invalid MIME type format',
          },
        },
      },

      size_mb: {
        type: DataTypes.DECIMAL,
      },

      width_px: {
        type: DataTypes.INTEGER,
      },

      height_px: {
        type: DataTypes.INTEGER,
      },

      duration_sec: {
        type: DataTypes.DECIMAL,
      },

      checksum: {
        type: DataTypes.TEXT,
      },

      is_public: {
        type: DataTypes.BOOLEAN,

        allowNull: false,
        defaultValue: false,
      },

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

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

    db.assets.hasMany(db.asset_variants, {
      as: 'asset_variants_asset',
      foreignKey: {
        name: 'assetId',
      },
      constraints: true,
      onDelete: 'CASCADE',
      onUpdate: 'CASCADE',
    });

    //end loop

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

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

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

  return assets;
};
