"use strict";

module.exports = {
  async up(queryInterface, Sequelize) {
    await queryInterface.createTable("MerchantWalletBalances", {
      id: {
        type: Sequelize.UUID,
        defaultValue: Sequelize.UUIDV4,
        primaryKey: true,
        allowNull: false,
      },
      merchantId: {
        type: Sequelize.UUID,
        allowNull: false,
        references: { model: "Merchants", key: "id" },
        onDelete: "CASCADE",
      },
      currency: {
        type: Sequelize.STRING(10),
        allowNull: false,
        comment: "Currency code, e.g. USD, EUR. NGN is never stored here — it lives on Merchant.balance.",
      },
      balance: {
        type: Sequelize.DECIMAL(20, 2),
        defaultValue: 0.00,
        allowNull: false,
      },
      prev_balance: {
        type: Sequelize.DECIMAL(20, 2),
        defaultValue: 0.00,
        allowNull: false,
      },
      status: {
        type: Sequelize.ENUM("active", "inactive"),
        defaultValue: "active",
        allowNull: false,
        comment: "Mirrors the owning Currency's virtualAccountStatus — toggled by the daily wallet-currency sync, not deleted.",
      },
      createdAt: {
        type: Sequelize.DATE,
        allowNull: false,
        defaultValue: Sequelize.literal("NOW()"),
      },
      updatedAt: {
        type: Sequelize.DATE,
        allowNull: false,
        defaultValue: Sequelize.literal("NOW()"),
      },
    });

    // Composite unique index: one balance record per merchant per currency
    await queryInterface.addIndex("MerchantWalletBalances", ["merchantId", "currency"], {
      unique: true,
      name: "unique_merchant_wallet_balance",
    });
  },

  async down(queryInterface) {
    await queryInterface.dropTable("MerchantWalletBalances");
  },
};
