import { DataTypes } from "sequelize";

export default (sequelize) => {
  const Transaction = sequelize.define("Transaction", {
    id: {
      type: DataTypes.UUID,
      defaultValue: DataTypes.UUIDV4,
      primaryKey: true,
    },
    merchantId: {
        type: DataTypes.UUID,
        allowNull: false,
    },
    customerId: {
      type: DataTypes.UUID,
      allowNull: true, // Null if it's a merchant-only transaction
    },
    transaction_id: {
      type: DataTypes.STRING,
      allowNull: false, // Internal session or reference ID
    },
    type: {
      type: DataTypes.ENUM("debit", "credit"),
      allowNull: false,
    },
    class: {
        type: DataTypes.ENUM("payout", "deposit", "transfer"),
        allowNull: false,
    },
    amount: {
      type: DataTypes.DECIMAL(20, 2),
      allowNull: false,
    },
    fee: {
      type: DataTypes.DECIMAL(20, 2),
      defaultValue: 0.00,
    },
    total_amount: {
      type: DataTypes.DECIMAL(20, 2),
      allowNull: false,
    },
    stampDuty: {
      type: DataTypes.DECIMAL(20, 2),
      defaultValue: 0.00,
    },
    status: {
      type: DataTypes.ENUM("pending", "success", "failed"),
      defaultValue: "pending",
    },
    info: {
      type: DataTypes.TEXT,
      allowNull: true,
    },
    currency: {
      type: DataTypes.STRING,
      defaultValue: "NGN",
    },
    reconciliationAttempts: {
      type: DataTypes.INTEGER,
      defaultValue: 0,
      allowNull: false,
    },
    old_balance: {
      type: DataTypes.DECIMAL(20, 2),
      allowNull: true,
      comment: "Balance of the primary affected account (customer if set, otherwise merchant) immediately before this transaction's balance change.",
    },
    new_balance: {
      type: DataTypes.DECIMAL(20, 2),
      allowNull: true,
      comment: "Balance of the primary affected account (customer if set, otherwise merchant) immediately after this transaction's balance change.",
    },
  }, {
    timestamps: true,
  });

  Transaction.associate = (models) => {
    Transaction.belongsTo(models.Merchant, { foreignKey: "merchantId" });
    Transaction.belongsTo(models.Customer, { foreignKey: "customerId" });
  };

  return Transaction;
};
