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

      variant_type: {
        type: DataTypes.ENUM,

        values: [
          'thumbnail',

          'preview',

          'webp',

          'mp4_low',

          'mp4_high',

          'original',
        ],
      },

      cdn_url: {
        type: DataTypes.TEXT,
        validate: {
          len: {
            args: [0, 2048],
            msg: 'CDN URL must be at most 2048 characters',
          },
          isUrlOrEmpty(value) {
            if (value && value.length > 0 && !/^https?:\/\/.+/.test(value)) {
              throw new Error('CDN URL must be a valid URL');
            }
          },
        },
      },

      width_px: {
        type: DataTypes.INTEGER,
        validate: {
          min: { args: [0], msg: 'Width must be a non-negative integer' },
        },
      },

      height_px: {
        type: DataTypes.INTEGER,
        validate: {
          min: { args: [0], msg: 'Height must be a non-negative integer' },
        },
      },

      size_mb: {
        type: DataTypes.DECIMAL,
        validate: {
          min: { args: [0], msg: 'Size must be a non-negative number' },
        },
      },

      importHash: {
        type: DataTypes.STRING(255),
        allowNull: true,
        unique: true,
      },
    },
    {
      timestamps: true,
      paranoid: true,
      freezeTableName: true,
    },
  );

  asset_variants.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.asset_variants.belongsTo(db.assets, {
      as: 'asset',
      foreignKey: {
        name: 'assetId',
      },
      constraints: true,
      onDelete: 'CASCADE',
      onUpdate: 'CASCADE',
    });

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

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

  return asset_variants;
};
