/* eslint-disable no-await-in-loop */
import { DataTypes } from 'sequelize';

import { Migration, safeApplyColumnChanges } from '../migrate';

export const up: Migration = async ({ context }) => {
  await safeApplyColumnChanges(context, {
    subscriptions: [
      {
        name: 'proration_behavior',
        field: { type: DataTypes.ENUM('always_invoice', 'create_prorations', 'none'), defaultValue: 'none' },
      },
      {
        name: 'payment_behavior',
        field: {
          type: DataTypes.ENUM(
            'default_incomplete',
            'allow_incomplete',
            'error_if_incomplete',
            'pending_if_incomplete'
          ),
          defaultValue: 'default_incomplete',
        },
      },
    ],
    customers: [
      {
        name: 'token_balance',
        // NOTE: we must use stringified empty object as default value here
        field: { type: DataTypes.JSON, defaultValue: '{}' },
      },
    ],
    invoices: [
      {
        name: 'starting_token_balance',
        field: { type: DataTypes.JSON, defaultValue: '{}' },
      },
      {
        name: 'ending_token_balance',
        field: { type: DataTypes.JSON, defaultValue: '{}' },
      },
    ],
  });
};

export const down: Migration = async ({ context }) => {
  await context.removeColumn('subscriptions', 'proration_behavior');
  await context.removeColumn('subscriptions', 'payment_behavior');
  await context.removeColumn('customers', 'token_balance');
};
