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

module.exports = (sequelize) => {
	const AssetLoan = sequelize.define(
		"assetloan",
		{
			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: true },
			owner: { type: DataTypes.INTEGER, allowNull: true },
			createdAt: { type: DataTypes.DATE, allowNull: true, field: "createdAt" },
			updatedAt: { type: DataTypes.DATE, allowNull: true, field: "updatedAt" },

			loan_number: { type: DataTypes.STRING(50), allowNull: true, unique: true },
			borrower_employee_id: { type: DataTypes.INTEGER, allowNull: true },
			department_id: { type: DataTypes.INTEGER, allowNull: true },
			designation_id: { type: DataTypes.INTEGER, allowNull: true },
			position: { type: DataTypes.STRING(255), allowNull: true },
			loan_date: { type: DataTypes.DATEONLY, allowNull: true },
			return_date: { type: DataTypes.DATEONLY, allowNull: true },
			actual_return_date: { type: DataTypes.DATEONLY, allowNull: true },
			purpose: { type: DataTypes.TEXT, allowNull: true },
			status: {
				type: DataTypes.ENUM("draft", "approved", "returned", "cancelled", "Need Approval", "Rejected"),
				allowNull: false,
				defaultValue: "draft"
			},
			notes: { type: DataTypes.TEXT, allowNull: true },
			company_id: { type: DataTypes.INTEGER, allowNull: true },

			// Workflow fields
			submitted_date: { type: DataTypes.DATE, allowNull: true },
			approver_date: { type: DataTypes.DATE, allowNull: true },
			cancel_reason: { type: DataTypes.TEXT, allowNull: true },
			revision_notes: { type: DataTypes.TEXT, allowNull: true },
			rejection_reason: { type: DataTypes.TEXT, allowNull: true },
			workflow_id: { type: DataTypes.INTEGER, allowNull: true, defaultValue: null },
		},
		{
			tableName: "assetloans",
			freezeTableName: true,
			indexes: [
				{ name: "idx_assetloans_company_id", fields: ["company_id"] },
				{ name: "idx_assetloans_borrower", fields: ["borrower_employee_id"] },
				{ name: "idx_assetloans_designation_id", fields: ["designation_id"] },
				{ name: "idx_assetloans_status", fields: ["status"] },
			],
		}
	);

	AssetLoan.associate = (models) => {
		AssetLoan.belongsTo(models.Company, { foreignKey: "company_id", as: "company" });
		AssetLoan.belongsTo(models.Employee, { foreignKey: "borrower_employee_id", as: "borrower" });
		AssetLoan.belongsTo(models.Department, { foreignKey: "department_id", as: "department" });
		AssetLoan.belongsTo(models.Designation, { foreignKey: "designation_id", as: "designation" });
		AssetLoan.hasMany(models.AssetLoanItem, { foreignKey: "loan_id", as: "items" });
	};

	return AssetLoan;
};
