const {DataTypes} = require("sequelize")

module.exports = (sequelize) => {
  return sequelize.define(
    "DerivativePosition",
    {
      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 },
      order_id: { type: DataTypes.BIGINT.UNSIGNED, allowNull: false },
      side: { type: DataTypes.ENUM("long", "short"), allowNull: false },
      leverage: { type: DataTypes.INTEGER, allowNull: false, defaultValue: 1 },
      position_mode: { type: DataTypes.ENUM("cross", "isolated"), allowNull: false, defaultValue: "cross" },
      isolated_margin: { type: DataTypes.DECIMAL(30, 12), allowNull: true },
      qty: { type: DataTypes.DECIMAL(30, 12), allowNull: false },
      entry_price: { type: DataTypes.DECIMAL(30, 12), allowNull: false },
      mark_price: { type: DataTypes.DECIMAL(30, 12), allowNull: true },
      unrealized_pnl: { type: DataTypes.DECIMAL(30, 12), allowNull: false, defaultValue: 0 },
      realized_pnl: { type: DataTypes.DECIMAL(30, 12), allowNull: false, defaultValue: 0 },
      liquidation_price: { type: DataTypes.DECIMAL(30, 12), allowNull: true },
      stop_loss: { type: DataTypes.DECIMAL(30, 12), allowNull: true },
      take_profit: { type: DataTypes.DECIMAL(30, 12), allowNull: true },
      status: { type: DataTypes.ENUM("open", "closed", "liquidating"), allowNull: false, defaultValue: "open" },
      opened_at: { type: DataTypes.DATE, allowNull: false, defaultValue: DataTypes.NOW },
      closed_at: { type: DataTypes.DATE, allowNull: true },
    },
    {
      tableName: "derivative_positions",
      underscored: true,
      timestamps: false,
      indexes: [
        { fields: ["account_id", "status"] },
        { fields: ["market_id", "status"] },
      ],
    }
  );
};