import { DataTypes } from 'sequelize';

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

export const up: Migration = async ({ context }) => {
  await context.createTable('meters', models.Meter.GENESIS_ATTRIBUTES);
  await context.createTable('meter_events', models.MeterEvent.GENESIS_ATTRIBUTES);
  await context.createTable('credit_grants', models.CreditGrant.GENESIS_ATTRIBUTES);
  await context.createTable('credit_transactions', models.CreditTransaction.GENESIS_ATTRIBUTES);

  await safeApplyColumnChanges(context, {
    payment_currencies: [
      {
        name: 'type',
        field: {
          type: DataTypes.ENUM('standard', 'credit'),
          defaultValue: 'standard',
          allowNull: false,
        },
      },
    ],
  });

  await context.sequelize.query(`
    UPDATE payment_currencies 
    SET maximum_precision = decimal 
    WHERE payment_method_id IN (
      SELECT id FROM payment_methods WHERE type = 'stripe'
    );
  `);
};

export const down: Migration = async ({ context }) => {
  await context.removeColumn('payment_currencies', 'type');
  await context.dropTable('credit_transactions');
  await context.dropTable('credit_grants');
  await context.dropTable('meter_events');
  await context.dropTable('meters');
};
