'use strict';

module.exports = {
  async up(queryInterface, Sequelize) {
    await queryInterface.sequelize.query(`
      ALTER TABLE sessions ALTER COLUMN status DROP DEFAULT;
      ALTER TABLE sessions ALTER COLUMN status TYPE VARCHAR(32) USING status::text;
      UPDATE sessions
      SET status = CASE
        WHEN status = 'shared' THEN 'shared'
        WHEN status = 'draft_review' THEN 'draft'
        WHEN status = 'completed' THEN 'draft'
        ELSE status
      END;
      ALTER TABLE sessions ALTER COLUMN status SET DEFAULT 'draft';
      ALTER TABLE sessions ALTER COLUMN status SET NOT NULL
    `);
    await queryInterface.addColumn('sessions', 'revision', {
      type: Sequelize.INTEGER,
      allowNull: false,
      defaultValue: 1,
    });
    await queryInterface.addColumn('sessions', 'approved_at', { type: Sequelize.DATE });
    await queryInterface.addColumn('sessions', 'approved_by_id', { type: Sequelize.UUID });
    await queryInterface.addColumn('sessions', 'shared_at', { type: Sequelize.DATE });
    await queryInterface.addColumn('sessions', 'shared_by_id', { type: Sequelize.UUID });
    await queryInterface.addColumn('sessions', 'unshared_at', { type: Sequelize.DATE });
    await queryInterface.addColumn('sessions', 'unshared_by_id', { type: Sequelize.UUID });
  },

  async down(queryInterface, Sequelize) {
    await queryInterface.removeColumn('sessions', 'unshared_by_id');
    await queryInterface.removeColumn('sessions', 'unshared_at');
    await queryInterface.removeColumn('sessions', 'shared_by_id');
    await queryInterface.removeColumn('sessions', 'shared_at');
    await queryInterface.removeColumn('sessions', 'approved_by_id');
    await queryInterface.removeColumn('sessions', 'approved_at');
    await queryInterface.removeColumn('sessions', 'revision');
    await queryInterface.changeColumn('sessions', 'status', {
      type: Sequelize.ENUM('planned', 'completed', 'draft_review', 'shared'),
      defaultValue: 'completed',
    });
  },
};
