const { DataTypes } = require("sequelize")

module.exports = (sequelize) => {
  return sequelize.define(
    "DerivativeOrder",
    {
      id: { type: DataTypes.BIGINT.UNSIGNED, primaryKey: true, autoIncrement: true },
      userId: { type: DataTypes.BIGINT.UNSIGNED, allowNull: false, field: 'user_id' },
      account_id: { type: DataTypes.BIGINT.UNSIGNED, allowNull: false },
      market_id: { type: DataTypes.BIGINT.UNSIGNED, allowNull: false },

      side: { type: DataTypes.ENUM("long", "short"), allowNull: false },
      type: {
        type: DataTypes.ENUM("market", "limit", "stop", "stop_limit", "take_profit", "stop_loss"),
        allowNull: false,
      },

      price: { type: DataTypes.DECIMAL(30, 12), allowNull: true },
      trigger_price: { type: DataTypes.DECIMAL(30, 12), allowNull: true },

      qty: { type: DataTypes.DECIMAL(30, 12), allowNull: false },
      qty_filled: { type: DataTypes.DECIMAL(30, 12), allowNull: false, defaultValue: 0 },

      leverage: { type: DataTypes.INTEGER, allowNull: false, defaultValue: 1 },
      reduce_only: { type: DataTypes.BOOLEAN, allowNull: false, defaultValue: false },

      status: {
        type: DataTypes.ENUM("new", "partially_filled", "filled", "canceled", "rejected"),
        allowNull: false,
        defaultValue: "new",
      },

      client_order_id: { type: DataTypes.STRING(64), allowNull: true },
    },
    {
      tableName: "derivative_orders",
      underscored: true,
      timestamps: true,
      indexes: [
        { fields: ["account_id", "status"] },
        { fields: ["market_id", "status"] },
        { fields: ["market_id", "type", "trigger_price", "status"] },
        { unique: true, fields: ["account_id", "client_order_id"] },
      ],
    }
  );
};