import { loadConfig } from '../core/config.js'
import { BybitRestClient } from '../lib/bybit/rest.js'
import { parseCliArgs } from '../utils.js'

async function main(): Promise<void> {
  const args = parseCliArgs(process.argv.slice(2))
  const config = loadConfig()
  const client = new BybitRestClient({
    demoApiKey: config.demoApiKey,
    demoApiSecret: config.demoApiSecret,
    recvWindow: config.recvWindow
  })

  const side = String(args.side ?? args._[0] ?? 'Buy')
  const qty = String(args.qty ?? args._[1] ?? '')
  const category = String(args.category ?? config.defaultCategory)
  const symbol = String(args.symbol ?? config.defaultSymbol)
  const orderType = String(args.orderType ?? 'Market')
  const price = args.price ? String(args.price) : undefined
  const reduceOnly = Boolean(args.reduceOnly)

  if (!qty) {
    throw new Error('Usage: npm run order:place -- --side Buy --qty 0.001 --category linear --symbol BTCUSDT [--orderType Limit --price 60000] [--reduceOnly]')
  }

  const payload: Record<string, unknown> = {
    category,
    symbol,
    side,
    orderType,
    qty,
    reduceOnly
  }

  if (price) {
    payload.price = price
    payload.timeInForce = 'GTC'
  }

  const result = await client.placeOrder(payload)
  console.log(JSON.stringify(result, null, 2))
}

main().catch(error => {
  console.error(error)
  process.exit(1)
})
