"use strict";

module.exports = {
  async up(queryInterface, Sequelize) {
    await queryInterface.createTable("CustomerServiceBalances", {
      id: {
        type: Sequelize.UUID,
        defaultValue: Sequelize.UUIDV4,
        primaryKey: true,
        allowNull: false,
      },
      customerId: {
        type: Sequelize.UUID,
        allowNull: false,
        references: { model: "Customers", key: "id" },
        onDelete: "CASCADE",
      },
      serviceId: {
        type: Sequelize.UUID,
        allowNull: false,
        references: { model: "SystemServices", key: "id" },
        onDelete: "CASCADE",
      },
      balance: {
        type: Sequelize.DECIMAL(20, 2),
        defaultValue: 0.00,
        allowNull: false,
      },
      prev_balance: {
        type: Sequelize.DECIMAL(20, 2),
        defaultValue: 0.00,
        allowNull: false,
      },
      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 customer per service
    await queryInterface.addIndex("CustomerServiceBalances", ["customerId", "serviceId"], {
      unique: true,
      name: "unique_customer_service_balance",
    });
  },

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