const { DataTypes } = require("sequelize");

module.exports = (sequelize) => {
	const MediaFolder = sequelize.define(
		"mediafolder",
		{
			id: {
				type: DataTypes.INTEGER,
				autoIncrement: true,
				primaryKey: true,
			},
			creation: { type: DataTypes.DATE, allowNull: false },
			modified: { type: DataTypes.DATE, allowNull: false },
			modified_by: { type: DataTypes.INTEGER, allowNull: false },
			owner: { type: DataTypes.INTEGER, allowNull: false },
			enabled: {
				type: DataTypes.BOOLEAN,
				allowNull: false,
				defaultValue: true,
			},

			// main fields
			name: { type: DataTypes.STRING(100), allowNull: false },
			slug: { type: DataTypes.STRING(100), allowNull: false },
			description: { type: DataTypes.TEXT, allowNull: true },

			// foreign keys
			company_id: {
				type: DataTypes.INTEGER,
				allowNull: true,
			},
			parent_id: {
				type: DataTypes.INTEGER,
				allowNull: true,
			},
		},
		{
			tableName: "mediafolders",
			freezeTableName: true
		}
	);

	MediaFolder.associate = (models) => {
		// Belongs to Company
		MediaFolder.belongsTo(models.Company, {
			foreignKey: "company_id",
			as: "company",
		});

		// Self-referential for parent folder
		MediaFolder.belongsTo(models.MediaFolder, {
			foreignKey: "parent_id",
			as: "parent",
		});

		// Has many Media items
		MediaFolder.hasMany(models.Media, {
			foreignKey: "folder_id",
			as: "media_items",
		});

		// Has many subfolders
		MediaFolder.hasMany(models.MediaFolder, {
			foreignKey: "parent_id",
			as: "subfolders",
		});
	};

	return MediaFolder;
};
