import { DataTypes } from 'sequelize';
import { createIndexIfNotExists, safeApplyColumnChanges, type Migration } from '../migrate';

export const up: Migration = async ({ context }) => {
  // Add new columns to credit_transactions table
  await safeApplyColumnChanges(context, {
    credit_transactions: [
      {
        name: 'transfer_status',
        field: {
          type: DataTypes.ENUM('pending', 'completed', 'failed'),
          allowNull: true,
        },
      },
      {
        name: 'transfer_hash',
        field: {
          type: DataTypes.STRING(255),
          allowNull: true,
        },
      },
    ],
  });

  // Add new columns to credit_grants table for on-chain operations
  await safeApplyColumnChanges(context, {
    credit_grants: [
      {
        name: 'chain_status',
        field: {
          type: DataTypes.ENUM(
            'mint_pending',
            'mint_completed',
            'mint_failed',
            'burn_pending',
            'burn_completed',
            'burn_failed'
          ),
          allowNull: true,
        },
      },
      {
        name: 'chain_detail',
        field: {
          type: DataTypes.JSON,
          allowNull: true,
        },
      },
    ],
  });

  // Add indexes for efficient querying
  await createIndexIfNotExists(
    context,
    'credit_transactions',
    ['transfer_status'],
    'idx_credit_transactions_transfer_status'
  );
  await createIndexIfNotExists(context, 'credit_grants', ['chain_status'], 'idx_credit_grants_chain_status');
};

export const down: Migration = async ({ context }) => {
  // Remove indexes
  await context.removeIndex('credit_transactions', 'idx_credit_transactions_transfer_status');
  await context.removeIndex('credit_grants', 'idx_credit_grants_chain_status');

  // Remove columns from credit_transactions
  await context.removeColumn('credit_transactions', 'transfer_hash');
  await context.removeColumn('credit_transactions', 'transfer_status');

  // Remove columns from credit_grants
  await context.removeColumn('credit_grants', 'chain_detail');
  await context.removeColumn('credit_grants', 'chain_status');
};
