const { DataTypes } = require("sequelize");

module.exports = (sequelize) => {
  const BinaryTrade = sequelize.define(
    "BinaryTrade",
    {
      userId: { type: DataTypes.INTEGER, allowNull: false },

      walletType: {
        type: DataTypes.ENUM("real", "demo"),
        allowNull: false,
        defaultValue: "demo",
      },

      assetId: { type: DataTypes.INTEGER, allowNull: false },
      assetSymbol: { type: DataTypes.STRING, allowNull: false },

      direction: {
        type: DataTypes.ENUM("buy", "sell"),
        allowNull: false,
      },

      investment: { type: DataTypes.DECIMAL(18, 4), allowNull: false },
      payoutPercent: { type: DataTypes.DECIMAL(8, 4), allowNull: false },

      potentialProfit: {
        type: DataTypes.DECIMAL(18, 4),
        allowNull: false,
        defaultValue: 0,
      },

      potentialReturn: {
        type: DataTypes.DECIMAL(18, 4),
        allowNull: false,
        defaultValue: 0,
      },

      entryPrice: { type: DataTypes.DECIMAL(18, 6), allowNull: false },
      resultPrice: { type: DataTypes.DECIMAL(18, 6), allowNull: true },

      entryPriceLockedAt: {
        type: DataTypes.DATE,
        allowNull: false,
        defaultValue: DataTypes.NOW,
      },

      expiresAt: { type: DataTypes.DATE, allowNull: false },
      settledAt: { type: DataTypes.DATE, allowNull: true },

      durationSeconds: { type: DataTypes.INTEGER, allowNull: false },

      status: {
        type: DataTypes.ENUM("open", "won", "lost", "draw", "cancelled"),
        allowNull: false,
        defaultValue: "open",
      },

      profit: {
        type: DataTypes.DECIMAL(18, 4),
        allowNull: false,
        defaultValue: 0,
      },

      payoutAmount: {
        type: DataTypes.DECIMAL(18, 4),
        allowNull: false,
        defaultValue: 0,
      },

      meta: { type: DataTypes.JSON, allowNull: true },
    },
    {
      tableName: "binary_trades",
      underscored: true,
      timestamps: true,
      indexes: [
        { fields: ["user_id", "status"] },
        { fields: ["asset_id", "status"] },
        { fields: ["expires_at", "status"] },
        { fields: ["asset_symbol", "created_at"] },
      ],
    }
  );

  return BinaryTrade;
};