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

module.exports = (sequelize) => {
	const UserCompany = sequelize.define(
		"usercompanie",
		{
			user_id: {
				type: DataTypes.INTEGER,
				references: {
					model: "users",
					key: "id",
					primaryKey: true,
				},
			},
			company_id: {
				type: DataTypes.INTEGER,
				references: {
					model: "companies",
					key: "id",
					primaryKey: true,
				},
			},
		},
		{
			tableName: "usercompanies",
			freezeTableName: true,
			indexes: [
				// OPTIMIZATION: Index on user_id for fast lookup
				{
					name: "idx_usercompanies_user_id",
					fields: ["user_id"],
				},
				// OPTIMIZATION: Index on company_id for fast lookup
				{
					name: "idx_usercompanies_company_id",
					fields: ["company_id"],
				},
				// OPTIMIZATION: Composite index for user_id + company_id queries
				{
					name: "idx_usercompanies_user_company",
					fields: ["user_id", "company_id"],
				},
			],
		}
	);

	UserCompany.associate = (models) => {
		UserCompany.belongsTo(models.User, {
			foreignKey: "user_id",
			as: "user",
		});

		UserCompany.belongsTo(models.Company, {
			foreignKey: "company_id",
			as: "company",
		});
	};

	return UserCompany;
};
