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

module.exports = (sequelize) => {
	const TeamMember = sequelize.define(
		"teammember",
		{
			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 },
			enabled: {
				type: DataTypes.BOOLEAN,
				allowNull: false,
				defaultValue: true,
			},

			// main fields
			name: { type: DataTypes.STRING(100), allowNull: false },
			position: { type: DataTypes.STRING(100), allowNull: false },
			bio: { type: DataTypes.TEXT, allowNull: true },
			order: { type: DataTypes.INTEGER, allowNull: false, defaultValue: 0 },

			// contact info
			email: { type: DataTypes.STRING(100), allowNull: true },
			phone: { type: DataTypes.STRING(20), allowNull: true },

			// social media
			social_links: {
				type: DataTypes.JSON,
				allowNull: true,
				defaultValue: {
					linkedin: "",
					twitter: "",
					facebook: "",
					instagram: "",
				},
			},

			// foreign keys
			company_id: {
				type: DataTypes.INTEGER,
				allowNull: true,
			},
			photo_id: {
				type: DataTypes.INTEGER,
				allowNull: true,
			},
			department_id: {
				type: DataTypes.INTEGER,
				allowNull: true,
			},
		},
		{
			tableName: "teammembers",
			freezeTableName: true,
		}
	);

	TeamMember.associate = (models) => {
		// Belongs to Company
		TeamMember.belongsTo(models.Company, {
			foreignKey: "company_id",
			as: "company",
		});

		// Belongs to Media for photo
		TeamMember.belongsTo(models.Media, {
			foreignKey: "photo_id",
			as: "photo",
		});

		// Belongs to Department (optional)
		TeamMember.belongsTo(models.Department, {
			foreignKey: "department_id",
			as: "department",
		});

		// Many-to-many with Sections
		TeamMember.belongsToMany(models.Section, {
			through: "section_team_members",
			foreignKey: "team_member_id",
			as: "sections",
		});
	};

	return TeamMember;
};
