/**
 * Migration to add Google OAuth support to users table
 * Adds:
 * - source column to track authentication method (local/google)
 * - last_login column to track last login time
 * - Makes password nullable for OAuth users
 */

module.exports = {
  async up(queryInterface, Sequelize) {
    // Add source column (default 'local' for existing users)
    await queryInterface.addColumn('users', 'source', {
      type: Sequelize.STRING,
      allowNull: false,
      defaultValue: 'local',
      comment: 'Authentication source: local (email/password) or google (OAuth)',
    });

    // Add last_login column
    await queryInterface.addColumn('users', 'last_login', {
      type: Sequelize.DATE,
      allowNull: true,
      comment: 'Timestamp of last successful login',
    });

    // Make password nullable for OAuth users
    await queryInterface.changeColumn('users', 'password', {
      type: Sequelize.STRING,
      allowNull: true,
    });

    // Add index on source column for faster filtering
    await queryInterface.addIndex('users', ['source'], {
      name: 'users_source_idx',
    });

    // Add index on last_login for analytics queries
    await queryInterface.addIndex('users', ['last_login'], {
      name: 'users_last_login_idx',
    });
  },

  async down(queryInterface, Sequelize) {
    // Remove indexes
    await queryInterface.removeIndex('users', 'users_last_login_idx');
    await queryInterface.removeIndex('users', 'users_source_idx');

    // Remove columns
    await queryInterface.removeColumn('users', 'last_login');
    await queryInterface.removeColumn('users', 'source');

    // Restore password to NOT NULL (this might fail if OAuth users exist)
    await queryInterface.changeColumn('users', 'password', {
      type: Sequelize.STRING,
      allowNull: false,
    });
  },
};
