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

module.exports = (sequelize) => {
	const Testimonial = sequelize.define(
		"testimonial",
		{
			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
			client_name: { type: DataTypes.STRING(100), allowNull: false },
			client_position: { type: DataTypes.STRING(100), allowNull: true },
			client_company: { type: DataTypes.STRING(100), allowNull: true },
			content: { type: DataTypes.TEXT, allowNull: false },
			rating: {
				type: DataTypes.INTEGER,
				allowNull: true,
				validate: { min: 1, max: 5 },
			},
			is_featured: {
				type: DataTypes.BOOLEAN,
				allowNull: false,
				defaultValue: false,
			},
			testimonial_date: { type: DataTypes.DATEONLY, allowNull: true },

			// foreign keys
			company_id: {
				type: DataTypes.INTEGER,
				allowNull: true,
			},
			client_photo_id: {
				type: DataTypes.INTEGER,
				allowNull: true,
			},
			project_id: {
				type: DataTypes.INTEGER,
				allowNull: true,
			},
		},
		{
			tableName: "testimonials",
			freezeTableName: true,
		}
	);

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

		// Belongs to Media for client photo
		Testimonial.belongsTo(models.Media, {
			foreignKey: "client_photo_id",
			as: "client_photo",
		});

		// Belongs to Project (optional)
		Testimonial.belongsTo(models.Project, {
			foreignKey: "project_id",
			as: "project",
		});

		// Many-to-many with Sections
		Testimonial.belongsToMany(models.Section, {
			through: "section_testimonials",
			foreignKey: "testimonial_id",
			as: "sections",
		});
	};

	return Testimonial;
};
