'use strict';

/**
 * Menambah composite index (connection_status, attempt_timestamp) pada connection_attempts.
 * Mengoptimalkan getRecentFailures dan query dengan filter status + waktu.
 * Idempoten: cek dulu apakah indeks sudah ada.
 */

module.exports = {
	async up(queryInterface) {
		const table = 'connection_attempts';
		const indexName = 'idx_connection_attempts_status_timestamp';
		const [indexes] = await queryInterface.sequelize.query(
			`SHOW INDEX FROM \`${table}\` WHERE Key_name = ?`,
			{ replacements: [indexName] }
		);
		if (Array.isArray(indexes) && indexes.length > 0) {
			// Index sudah ada, skip
			return;
		}
		await queryInterface.addIndex(table, ['connection_status', 'attempt_timestamp'], {
			name: indexName,
		});
	},

	async down(queryInterface) {
		const table = 'connection_attempts';
		const indexName = 'idx_connection_attempts_status_timestamp';
		try {
			await queryInterface.removeIndex(table, indexName);
		} catch (e) {
			// Index mungkin tidak ada
		}
	},
};
