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

module.exports = (sequelize) => {
	const Media = sequelize.define(
		"media",
		{
			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(255), allowNull: false },
			original_name: { type: DataTypes.STRING(255), allowNull: false },
			file_path: { type: DataTypes.STRING(512), allowNull: false },
			file_size: { type: DataTypes.INTEGER, allowNull: false }, // in bytes
			mime_type: { type: DataTypes.STRING(100), allowNull: false },
			extension: { type: DataTypes.STRING(20), allowNull: false },

			// metadata
			alt_text: { type: DataTypes.STRING(255), allowNull: true },
			caption: { type: DataTypes.STRING(512), allowNull: true },
			description: { type: DataTypes.TEXT, allowNull: true },
			dimensions: {
				type: DataTypes.JSON,
				allowNull: true,
				defaultValue: {}, // { width: 1920, height: 1080 }
			},

			// thumbnail data
			thumbnails: {
				type: DataTypes.JSON,
				allowNull: true,
				defaultValue: {}, // { small: 'path/to/small.jpg', medium: ... }
			},

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

	/**
	 * Associates the Media model with other models.
	 * @param {object} models - The models to associate with.
	 */
	Media.associate = (models) => {
		// Belongs to Company
		Media.belongsTo(models.Company, {
			foreignKey: "company_id",
			as: "company",
		});

		// Belongs to MediaFolder (optional)
		Media.belongsTo(models.MediaFolder, {
			foreignKey: "folder_id",
			as: "folder",
		});

		// Has many Section background images
		Media.hasMany(models.Section, {
			foreignKey: "background_image_id",
			as: "section_backgrounds",
		});

		// Has many SectionComponents
		Media.hasMany(models.SectionComponent, {
			foreignKey: "media_id",
			as: "components",
		});
	};

	return Media;
};
