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

module.exports = (sequelize) => {
	const AssetLocation = sequelize.define(
		"assetlocation",
		{
			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 },
			createdAt: { type: DataTypes.DATE, allowNull: true, field: "createdAt" },
			updatedAt: { type: DataTypes.DATE, allowNull: true, field: "updatedAt" },
			enabled: { type: DataTypes.BOOLEAN, allowNull: false, defaultValue: true },
			name: { type: DataTypes.STRING(150), allowNull: false },
			display_name: { type: DataTypes.STRING(150), allowNull: false },
			description: { type: DataTypes.TEXT, allowNull: true },
			address: { type: DataTypes.TEXT, allowNull: true },
			parent_id: { type: DataTypes.INTEGER, allowNull: true },
			company_id: { type: DataTypes.INTEGER, allowNull: true },
		},
		{
			tableName: "assetlocations",
			freezeTableName: true,
			indexes: [
				{ name: "idx_assetlocations_company_id", fields: ["company_id"] },
				{ name: "idx_assetlocations_enabled", fields: ["enabled"] },
				{ name: "idx_assetlocations_parent_id", fields: ["parent_id"] },
			],
		}
	);

	AssetLocation.associate = (models) => {
		AssetLocation.belongsTo(models.Company, { foreignKey: "company_id", as: "company" });
		AssetLocation.belongsTo(models.AssetLocation, { foreignKey: "parent_id", as: "parent" });
		AssetLocation.hasMany(models.AssetLocation, { foreignKey: "parent_id", as: "children" });
	};

	return AssetLocation;
};
