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

module.exports = (sequelize) => {
	const Section = sequelize.define(
		"section",
		{
			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
			section_type: {
				type: DataTypes.ENUM(
					"hero",
					"about",
					"services",
					"team",
					"testimonials",
					"contact",
					"custom"
				),
				allowNull: false,
			},
			title: { type: DataTypes.STRING(100), allowNull: true },
			subtitle: { type: DataTypes.STRING(255), allowNull: true },
			content: { type: DataTypes.TEXT, allowNull: true },
			order: { type: DataTypes.INTEGER, allowNull: false, defaultValue: 0 },

			// metadata (flexible JSON field for section-specific data)
			metadata: {
				type: DataTypes.JSON,
				allowNull: true,
				defaultValue: {},
			},

			// styling options
			style: {
				type: DataTypes.JSON,
				allowNull: true,
				defaultValue: {
					backgroundColor: "#ffffff",
					textColor: "#333333",
					paddingTop: "3rem",
					paddingBottom: "3rem",
				},
			},

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

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

		// Belongs to Media for background image
		Section.belongsTo(models.Media, {
			foreignKey: "background_image_id",
			as: "background_image",
		});

		// Has many SectionComponents for modular content
		Section.hasMany(models.SectionComponent, {
			foreignKey: "section_id",
			as: "components",
		});

		// For team sections - references TeamMember model
		Section.belongsToMany(models.TeamMember, {
			through: "section_team_members",
			foreignKey: "section_id",
			as: "team_members",
		});

		// For testimonial sections - references Testimonial model
		Section.belongsToMany(models.Testimonial, {
			through: "section_testimonials",
			foreignKey: "section_id",
			as: "testimonials",
		});
	};

	return Section;
};
