"use strict";

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

module.exports = (sequelize) => {
  const CopyTrade = sequelize.define(
    "CopyTrade",
    {
      id: {
        type: DataTypes.BIGINT.UNSIGNED,
        primaryKey: true,
        autoIncrement: true,
      },

      traderId: {
        type: DataTypes.BIGINT.UNSIGNED,
        allowNull: false,
        field: "trader_id",
      },

      pairId: {
        type: DataTypes.BIGINT.UNSIGNED,
        allowNull: false,
        field: "pair_id",
      },

      type: {
        type: DataTypes.ENUM("spot", "fx", "stock", "option", "terminal"),
        allowNull: false,
      },

      side: {
        type: DataTypes.ENUM("long", "short", "buy", "sell"),
        allowNull: false,
      },

      marketType: {
        type: DataTypes.STRING,
        allowNull: true,
        field: "market_type",
      },

      marketLimit: {
        type: DataTypes.ENUM("market", "limit", "stop-limit", "stop"),
        allowNull: true,
        field: "market_limit",
      },

      amount: {
        type: DataTypes.DECIMAL(30, 10),
        allowNull: true,
      },

      leverage: {
        type: DataTypes.INTEGER,
        allowNull: true,
      },

      payoutPercent: {
        type: DataTypes.DECIMAL(10, 4),
        allowNull: true,
        field: "payout_percent",
      },

      entryPrice: {
        type: DataTypes.DECIMAL(30, 10),
        allowNull: true,
        field: "entry_price",
      },

      closingPrice: {
        type: DataTypes.DECIMAL(30, 10),
        allowNull: true,
        field: "closing_price",
      },

      duration: {
        type: DataTypes.INTEGER,
        allowNull: true,
      },

      stopLoss: {
        type: DataTypes.DECIMAL(30, 10),
        allowNull: true,
        field: "stop_loss",
      },

      takeProfit: {
        type: DataTypes.DECIMAL(30, 10),
        allowNull: true,
        field: "take_profit",
      },

      profitAmount: {
        type: DataTypes.DECIMAL(30, 10),
        allowNull: true,
        defaultValue: 0,
        field: "profit_amount",
      },

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

      openedAt: {
        type: DataTypes.DATE,
        allowNull: true,
        field: "opened_at",
      },

      closedAt: {
        type: DataTypes.DATE,
        allowNull: true,
        field: "closed_at",
      },
    },
    {
      tableName: "copy_trades",
      underscored: true,
      timestamps: true, // handles created_at, updated_at

      indexes: [
        { fields: ["trader_id"] },
        { fields: ["pair_id"] },
        { fields: ["status"] },
      ],
    }
  );

  return CopyTrade;
};
