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

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

			item_id: { type: DataTypes.INTEGER, allowNull: false },
			item_type: { type: DataTypes.STRING(50), allowNull: false }, // asset, license, accessory, consumable, component
			action: { type: DataTypes.STRING(50), allowNull: false }, // checkout, checkin, update, maintenance, audit, consume

			target_id: { type: DataTypes.INTEGER, allowNull: true },
			target_type: { type: DataTypes.STRING(50), allowNull: true }, // Employee, Department, Asset, Location

			location_id: { type: DataTypes.INTEGER, allowNull: true },
			note: { type: DataTypes.TEXT, allowNull: true },
			filename: { type: DataTypes.STRING(255), allowNull: true },

			company_id: { type: DataTypes.INTEGER, allowNull: true },
		},
		{
			tableName: "assetlogs",
			freezeTableName: true,
			indexes: [
				{ name: "idx_assetlogs_item", fields: ["item_id", "item_type"] },
				{ name: "idx_assetlogs_company_id", fields: ["company_id"] },
				{ name: "idx_assetlogs_action", fields: ["action"] },
			],
		}
	);

	AssetLog.associate = (models) => {
		AssetLog.belongsTo(models.Company, { foreignKey: "company_id", as: "company" });
		AssetLog.belongsTo(models.User, { foreignKey: "modified_by", as: "executor" });
		AssetLog.belongsTo(models.AssetLocation, { foreignKey: "location_id", as: "location" });

		// Dynamic associations for targets
		AssetLog.belongsTo(models.Employee, { foreignKey: "target_id", constraints: false, as: "targetEmployee" });
		AssetLog.belongsTo(models.Department, { foreignKey: "target_id", constraints: false, as: "targetDepartment" });
		AssetLog.belongsTo(models.Asset, { foreignKey: "target_id", constraints: false, as: "targetAsset" });
	};

	return AssetLog;
};
