"use strict";

module.exports = {
	async up(queryInterface, Sequelize) {
		const tableName = "jobroles";

		const existingTablesRaw = await queryInterface.showAllTables();
		const existingTables = (existingTablesRaw || []).map((t) => (typeof t === "string" ? t : t?.tableName || t?.name)).filter(Boolean);
		const exists = existingTables.some((t) => String(t).toLowerCase() === tableName);
		if (exists) return;

		await queryInterface.createTable(tableName, {
			id: {
				type: Sequelize.INTEGER,
				autoIncrement: true,
				primaryKey: true,
				allowNull: false,
			},
			creation: { type: Sequelize.DATE, allowNull: false },
			modified: { type: Sequelize.DATE, allowNull: false },
			modified_by: { type: Sequelize.INTEGER, allowNull: false },
			owner: { type: Sequelize.INTEGER, allowNull: false },
			enabled: { type: Sequelize.BOOLEAN, allowNull: false, defaultValue: true },
			name: { type: Sequelize.STRING(100), allowNull: false },
			display_name: { type: Sequelize.STRING(100), allowNull: false },
			company_id: {
				type: Sequelize.INTEGER,
				allowNull: true,
				references: { model: "companies", key: "id" },
				onUpdate: "CASCADE",
				onDelete: "SET NULL",
			},
		});

		// Safe indexes (ignore if already exists)
		try {
			await queryInterface.addIndex(tableName, ["company_id", "name"], { name: "idx_jobroles_company_name" });
		} catch (_) {}
		try {
			await queryInterface.addIndex(tableName, ["company_id", "display_name"], { name: "idx_jobroles_company_display_name" });
		} catch (_) {}
	},

	async down(queryInterface) {
		const tableName = "jobroles";
		const existingTablesRaw = await queryInterface.showAllTables();
		const existingTables = (existingTablesRaw || []).map((t) => (typeof t === "string" ? t : t?.tableName || t?.name)).filter(Boolean);
		const exists = existingTables.some((t) => String(t).toLowerCase() === tableName);
		if (!exists) return;

		await queryInterface.dropTable(tableName);
	},
};
