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

module.exports = (sequelize) => {
	const Component = sequelize.define(
		'Component',
		{
			id: { type: DataTypes.INTEGER, primaryKey: true, autoIncrement: true },
			name: { type: DataTypes.STRING, allowNull: false },
			company_id: { type: DataTypes.INTEGER, allowNull: true },
			category_id: { type: DataTypes.INTEGER, allowNull: true },
			location_id: { type: DataTypes.INTEGER, allowNull: true },
			serial: { type: DataTypes.STRING, allowNull: true },
			qty: { type: DataTypes.INTEGER, defaultValue: 0 },
			min_amt: { type: DataTypes.INTEGER, defaultValue: 0 },
			purchase_date: { type: DataTypes.DATEONLY, allowNull: true },
			purchase_cost: { type: DataTypes.DECIMAL(13, 2), allowNull: true },
			order_number: { type: DataTypes.STRING, allowNull: true },
			notes: { type: DataTypes.TEXT, allowNull: true },
			image: { type: DataTypes.TEXT, allowNull: true },
			enabled: { type: DataTypes.TINYINT, defaultValue: 1 },
			creation: { type: DataTypes.DATE, defaultValue: DataTypes.NOW },
			modified: { type: DataTypes.DATE, defaultValue: DataTypes.NOW },
			owner: { type: DataTypes.INTEGER, allowNull: true },
			modified_by: { type: DataTypes.INTEGER, allowNull: true }
		},
		{
			tableName: 'components',
			timestamps: false
		}
	);

	Component.associate = (models) => {
		Component.belongsTo(models.Company, { foreignKey: 'company_id', as: 'company' });
		Component.belongsTo(models.AssetCategory, { foreignKey: 'category_id', as: 'category' });
		Component.belongsTo(models.AssetLocation, { foreignKey: 'location_id', as: 'location' });
		Component.hasMany(models.ComponentAsset, { foreignKey: 'component_id', as: 'componentAssets' });
	};

	return Component;
};
