"use strict";

/**
 * Add safe indexes to speed up Permissions/DocTypes loading.
 * Idempotent: checks via SHOW INDEX before creating.
 *
 * Tables:
 * - permissions: (role_id, doctype_id), (doctype_id)
 * - roles: (company_id, enabled)
 * - doctypes: (enabled, name)
 */

async function ensureIndex(queryInterface, table, indexName, columns) {
	const [rows] = await queryInterface.sequelize.query(`SHOW INDEX FROM \`${table}\``);
	if (Array.isArray(rows) && rows.length > 0) {
		const byKeyName = new Map();
		for (const row of rows) {
			const keyName = row.Key_name;
			if (!byKeyName.has(keyName)) byKeyName.set(keyName, []);
			byKeyName.get(keyName).push(row);
		}

		const wanted = columns;
		for (const [, keyRows] of byKeyName) {
			keyRows.sort((a, b) => Number(a.Seq_in_index) - Number(b.Seq_in_index));
			const existingCols = keyRows.map((r) => r.Column_name);
			const isPrefixMatch = wanted.every((col, i) => existingCols[i] === col);
			if (isPrefixMatch) return;
		}
	}

	await queryInterface.addIndex(table, columns, { name: indexName });
}

module.exports = {
	async up(queryInterface) {
		await ensureIndex(queryInterface, "permissions", "idx_permissions_role_doctype", ["role_id", "doctype_id"]);
		await ensureIndex(queryInterface, "permissions", "idx_permissions_doctype_id", ["doctype_id"]);
		await ensureIndex(queryInterface, "roles", "idx_roles_company_enabled", ["company_id", "enabled"]);
		await ensureIndex(queryInterface, "doctypes", "idx_doctypes_enabled_name", ["enabled", "name"]);
	},

	async down(queryInterface) {
		const removes = [
			["permissions", "idx_permissions_role_doctype"],
			["permissions", "idx_permissions_doctype_id"],
			["roles", "idx_roles_company_enabled"],
			["doctypes", "idx_doctypes_enabled_name"],
		];
		for (const [table, indexName] of removes) {
			try {
				await queryInterface.removeIndex(table, indexName);
			} catch (e) {
				// ignore if missing
			}
		}
	},
};
