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

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

			asset_id: { type: DataTypes.INTEGER, allowNull: false },
			supplier_id: { type: DataTypes.INTEGER, allowNull: true },
			maintenance_type: { type: DataTypes.STRING(50), allowNull: false }, // Repair, Upgrade, Routine, Hardware Support
			title: { type: DataTypes.STRING(150), allowNull: false },
			start_date: { type: DataTypes.DATEONLY, allowNull: true },
			completion_date: { type: DataTypes.DATEONLY, allowNull: true },
			asset_maintenance_time: { type: DataTypes.INTEGER, allowNull: true }, // Downtime in days
			cost: { type: DataTypes.DECIMAL(10, 2), allowNull: true },
			notes: { type: DataTypes.TEXT, allowNull: true },
			is_warranty: { type: DataTypes.BOOLEAN, allowNull: false, defaultValue: false },

			company_id: { type: DataTypes.INTEGER, allowNull: true },
		},
		{
			tableName: "assetmaintenances",
			freezeTableName: true,
			indexes: [
				{ name: "idx_maintenances_asset_id", fields: ["asset_id"] },
				{ name: "idx_maintenances_company_id", fields: ["company_id"] },
			],
		}
	);

	AssetMaintenance.associate = (models) => {
		AssetMaintenance.belongsTo(models.Company, { foreignKey: "company_id", as: "company" });
		AssetMaintenance.belongsTo(models.Asset, { foreignKey: "asset_id", as: "asset" });
		// AssetMaintenance.belongsTo(models.Supplier, { foreignKey: "supplier_id", as: "supplier" }); // Add when Supplier model exists
	};

	return AssetMaintenance;
};
