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

module.exports = (sequelize) => {
	const PlacementArea = sequelize.define(
		"placementarea",
		{
			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 },
			code: { type: DataTypes.STRING(10), allowNull: true },
			is_primary: { type: DataTypes.BOOLEAN, allowNull: false, defaultValue: true },
			description: { type: DataTypes.TEXT, allowNull: true },

			// fk
			parent_id: { type: DataTypes.INTEGER, allowNull: true },
			city_id: { type: DataTypes.INTEGER, allowNull: true },
			company_id: { type: DataTypes.INTEGER, allowNull: true },
		},
		{
			tableName: "placementareas",
			freezeTableName: true,
			indexes: [
				{ name: "idx_placementareas_company_id", fields: ["company_id"] },
				{ name: "idx_placementareas_enabled", fields: ["enabled"] },
				{ name: "idx_placementareas_is_primary", fields: ["is_primary"] },
				{ name: "idx_placementareas_parent_id", fields: ["parent_id"] },
				{ name: "idx_placementareas_city_id", fields: ["city_id"] },
			],
		}
	);

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

		PlacementArea.belongsTo(models.City, {
			foreignKey: "city_id",
			as: "city",
		});

		PlacementArea.belongsTo(models.PlacementArea, {
			foreignKey: "parent_id",
			as: "parent",
		});

		PlacementArea.hasMany(models.PlacementArea, {
			foreignKey: "parent_id",
			as: "children",
		});

		PlacementArea.hasMany(models.Employee, {
			foreignKey: "placement_area_id",
			as: "employees_primary",
		});

		PlacementArea.hasMany(models.Employee, {
			foreignKey: "secondary_placement_area_id",
			as: "employees_secondary",
		});
	};

	return PlacementArea;
};
