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

module.exports = (sequelize) => {
	const Zone = sequelize.define(
		"zone",
		{
			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 },

			// default timestamps (system pattern)
			createdAt: { type: DataTypes.DATE, allowNull: true, field: "createdAt" },
			updatedAt: { type: DataTypes.DATE, allowNull: true, field: "updatedAt" },

			// main
			name: { type: DataTypes.STRING(50), allowNull: false },
			display_name: { type: DataTypes.STRING(100), allowNull: false },
			description: { type: DataTypes.TEXT, allowNull: true },
			zone_order: { type: DataTypes.INTEGER, allowNull: true },

			// fk
			company_id: { type: DataTypes.INTEGER, allowNull: true },
		},
		{
			tableName: "zones",
			freezeTableName: true,
			indexes: [
				{ name: "idx_zones_company_id", fields: ["company_id"] },
				{ name: "idx_zones_enabled", fields: ["enabled"] },
				{ name: "idx_zones_zone_order", fields: ["zone_order"] },
			],
		}
	);

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

		Zone.hasMany(models.Employee, {
			foreignKey: "zone_id",
			as: "employees",
		});
	};

	return Zone;
};
