'use strict';

// Helper function to safely add a column if it doesn't exist
async function addColumnIfNotExists(queryInterface, tableName, columnName, columnDefinition) {
  const tableDescription = await queryInterface.describeTable(tableName);
  if (!tableDescription[columnName]) {
    await queryInterface.addColumn(tableName, columnName, columnDefinition);
  }
}

module.exports = {
  async up(queryInterface, Sequelize) {
    // Add last_session_at column to builds table
    // This enables sorting builds by most recent session activity (GitHub issue #1930)
    await addColumnIfNotExists(queryInterface, 'builds', 'last_session_at', {
      type: Sequelize.DATE,
      allowNull: true,
      comment: 'Timestamp of the most recent session created for this build',
    });

    // Backfill existing builds with the most recent session start_time
    await queryInterface.sequelize.query(`
      UPDATE builds
      SET last_session_at = subquery.max_start_time
      FROM (
        SELECT build_id, MAX(start_time) as max_start_time
        FROM sessions
        WHERE build_id IS NOT NULL
        GROUP BY build_id
      ) AS subquery
      WHERE builds.id = subquery.build_id;
    `);

    // Add index for efficient sorting by last_session_at
    const indexes = await queryInterface.showIndex('builds');
    const indexExists = indexes.some(idx => idx.name === 'builds_last_session_at_idx');
    if (!indexExists) {
      await queryInterface.addIndex('builds', ['last_session_at'], {
        name: 'builds_last_session_at_idx',
        order: [['last_session_at', 'DESC NULLS LAST']],
      });
    }
  },

  async down(queryInterface, Sequelize) {
    // Remove index first
    try {
      await queryInterface.removeIndex('builds', 'builds_last_session_at_idx');
    } catch (error) {
      // Index might not exist
    }

    // Remove column
    await queryInterface.removeColumn('builds', 'last_session_at');
  },
};
