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

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

			// main
			name: { type: DataTypes.STRING(150), allowNull: false },
			description: { type: DataTypes.TEXT, allowNull: true },
			notes: { type: DataTypes.TEXT, allowNull: true },
			fiscal_year: { type: DataTypes.INTEGER, allowNull: true },

			follow_via_email: { type: DataTypes.BOOLEAN, allowNull: true },
			budget_approver: { type: DataTypes.INTEGER, allowNull: true },
			finance_approver: { type: DataTypes.INTEGER, allowNull: true },
			posting_date: { type: DataTypes.DATE, allowNull: true },
			submitted_date: { type: DataTypes.DATE, allowNull: true },
			approver_date: { type: DataTypes.DATE, allowNull: true },
			status: { type: DataTypes.STRING, allowNull: true },

			cancel_reason: { type: DataTypes.TEXT, allowNull: true },
			revision_notes: { type: DataTypes.TEXT, allowNull: true },
			rejection_reason: { type: DataTypes.TEXT, allowNull: true },
			approval_notes: { type: DataTypes.TEXT, allowNull: true },

			// fk
			company_id: { type: DataTypes.INTEGER, allowNull: true },
			budgetdepartment_id: { type: DataTypes.INTEGER, allowNull: true },
		},
		{
			tableName: "budgetplans",
			freezeTableName: true,
		}
	);

	BudgetPlan.associate = (models) => {
		BudgetPlan.belongsTo(models.User, { foreignKey: "modified_by", as: "modifier" });
		BudgetPlan.belongsTo(models.Employee, { foreignKey: "budget_approver", as: "budgetapprover" });
		BudgetPlan.belongsTo(models.Employee, { foreignKey: "finance_approver", as: "financeapprover" });
		BudgetPlan.belongsTo(models.Company, { foreignKey: "company_id", as: "company" });
		BudgetPlan.belongsTo(models.BudgetDepartment, { foreignKey: "budgetdepartment_id", as: "budgetdepartment" });
		BudgetPlan.hasMany(models.BudgetPlanItem, { foreignKey: "budgetplan_id", as: "budgetplanitems" }); // One-to-many
	};

	return BudgetPlan;
};
