"use strict";
const { DataTypes } = require("sequelize");
const { generateRandomString } = require("../utils/helpers");

module.exports = (sequelize) => {
  const BotOrder = sequelize.define(
    "BotOrder",
    {
      id: { type: DataTypes.BIGINT.UNSIGNED, autoIncrement: true, primaryKey: true },
      reference: {type: DataTypes.STRING(20), allowNull: false, defaultValue: () => generateRandomString(16)},

      botInstanceId: {
        type: DataTypes.BIGINT.UNSIGNED,
        allowNull: false,
        field: "bot_instance_id",
      },

      symbol: { type: DataTypes.STRING(30), allowNull: false },

      side: { type: DataTypes.ENUM("buy", "sell"), allowNull: false },
      orderType: { type: DataTypes.ENUM("market", "limit", "stop"), allowNull: false, field: "order_type" },

      price: { type: DataTypes.DECIMAL(30, 18), allowNull: true },
      qty: { type: DataTypes.DECIMAL(30, 18), allowNull: false },

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

      exchangeOrderId: { type: DataTypes.STRING(80), allowNull: true, field: "exchange_order_id" },

      clientOrderId: { type: DataTypes.STRING(120), allowNull: false, field: "client_order_id" },

      actionId: { type: DataTypes.STRING(120), allowNull: true, field: "action_id" },

      raw: { type: DataTypes.JSON, allowNull: true },

      filledQty: { type: DataTypes.DECIMAL(30, 18), allowNull: false, defaultValue: 0, field: "filled_qty" },
      avgFillPrice: { type: DataTypes.DECIMAL(30, 18), allowNull: true, field: "avg_fill_price" },
    },
    {
      tableName: "bot_orders",
      underscored: true,
      timestamps: true,
      indexes: [
        { fields: ["bot_instance_id"] },
        { fields: ["symbol"] },
        { fields: ["status"] },
        { fields: ["exchange_order_id"] },
        { unique: true, fields: ["client_order_id"] }, // hard dedupe
      ],
    }
  );

  return BotOrder;
};
