'use strict';

// Helper function to safely create a table if it doesn't exist
async function createTableIfNotExists(queryInterface, tableName, tableDefinition) {
  const tableExists = await queryInterface.tableExists(tableName);
  if (!tableExists) {
    await queryInterface.createTable(tableName, tableDefinition);
  }
}

// Helper function to safely add an index if it doesn't exist
async function addIndexIfNotExists(queryInterface, tableName, fields, options) {
  try {
    // First check if table exists
    const tableExists = await queryInterface.tableExists(tableName);
    if (!tableExists) {
      // Table doesn't exist yet, skip index creation
      return;
    }

    // Check if index already exists
    const indexes = await queryInterface.showIndex(tableName);
    const indexName = options.name || `idx_${tableName}_${fields.join('_')}`;
    const indexExists = indexes.some(idx => idx.name === indexName);
    if (!indexExists) {
      await queryInterface.addIndex(tableName, fields, options);
    }
  } catch (error) {
    // If index already exists, ignore the error
    if (
      error.message &&
      (error.message.includes('already exists') ||
        error.message.includes('duplicate key value') ||
        (error.message.includes('relation') && error.message.includes('already exists')))
    ) {
      return;
    }
    // For other errors, try to add the index anyway (might be a different issue)
    // If it fails, the error will be more informative
    try {
      await queryInterface.addIndex(tableName, fields, options);
    } catch (addError) {
      // If it's still an "already exists" error, ignore it
      if (
        addError.message &&
        (addError.message.includes('already exists') ||
          addError.message.includes('duplicate key value') ||
          (addError.message.includes('relation') && addError.message.includes('already exists')))
      ) {
        return;
      }
      throw addError;
    }
  }
}

module.exports = {
  async up(queryInterface, Sequelize) {
    // Create wda table
    await createTableIfNotExists(queryInterface, 'wda', {
      id: {
        type: Sequelize.UUID,
        defaultValue: Sequelize.UUIDV4,
        primaryKey: true,
      },
      filepath: {
        type: Sequelize.STRING,
        allowNull: false,
        comment: 'Path to the WDA IPA file',
      },
      bundle_id: {
        type: Sequelize.STRING,
        allowNull: false,
        comment: 'Bundle identifier of the WDA app',
      },
      file_size: {
        type: Sequelize.DECIMAL(10, 2),
        allowNull: false,
        comment: 'File size in KB',
      },
      is_default: {
        type: Sequelize.BOOLEAN,
        defaultValue: false,
        allowNull: false,
        comment: 'Whether this is the default WDA to use',
      },
      uploaded_by: {
        type: Sequelize.UUID,
        allowNull: false,
        references: {
          model: 'users',
          key: 'id',
        },
        onUpdate: 'CASCADE',
        onDelete: 'RESTRICT',
        comment: 'User who uploaded this WDA file',
      },
      created_at: {
        type: Sequelize.DATE,
        defaultValue: Sequelize.NOW,
        allowNull: false,
      },
      updated_at: {
        type: Sequelize.DATE,
        defaultValue: Sequelize.NOW,
        allowNull: false,
      },
    });

    // Add indexes for efficient querying
    await addIndexIfNotExists(queryInterface, 'wda', ['uploaded_by'], {
      name: 'idx_wda_uploaded_by',
    });
    await addIndexIfNotExists(queryInterface, 'wda', ['is_default'], {
      name: 'idx_wda_is_default',
    });
    await addIndexIfNotExists(queryInterface, 'wda', ['bundle_id'], {
      name: 'idx_wda_bundle_id',
    });
    await addIndexIfNotExists(queryInterface, 'wda', ['created_at'], {
      name: 'idx_wda_created_at',
    });
  },

  async down(queryInterface, Sequelize) {
    await queryInterface.dropTable('wda');
  },
};
