import { describe, it, expect, vi } from "vitest";
import nacl from "tweetnacl";

import { PacificaWsOrderGateway } from "../packages/connectors/pacifica/src/wsOrderGateway";
import type { SigningConfig } from "../packages/connectors/pacifica/src/signing";

describe("PacificaWsOrderGateway", () => {
  const seed = Uint8Array.from({ length: 32 }, (_, i) => i + 1);
  const { secretKey, publicKey } = nacl.sign.keyPair.fromSeed(seed);
  const secret = Buffer.from(secretKey).toString("base64");
  const apiKey = Buffer.from(publicKey).toString("base64");

  const signing: SigningConfig = {
    apiKey,
    secret,
    subaccount: "sub-1"
  };

  it("extracts numeric order id from websocket response", async () => {
    const mockWs = {
      connect: vi.fn(),
      waitForOpen: vi.fn(),
      sendRpc: vi.fn().mockResolvedValue({ s: "BTC", i: 377323582, I: "client-1" })
    } as any;

    const gateway = new PacificaWsOrderGateway(mockWs, signing);
    const result = await gateway.createOrder({
      symbol: "BTC",
      side: "bid",
      price: "50000",
      amount: "0.1",
      tif: "IOC",
      clientOrderId: "client-1"
    });

    expect(result.orderId).toBe("377323582");
    expect(mockWs.sendRpc).toHaveBeenCalled();
  });

  it("throws when order id missing", async () => {
    const mockWs = {
      connect: vi.fn(),
      waitForOpen: vi.fn(),
      sendRpc: vi.fn().mockResolvedValue({ status: "ok" })
    } as any;

    const gateway = new PacificaWsOrderGateway(mockWs, signing);

    await expect(
      gateway.createOrder({
        symbol: "BTC",
        side: "bid",
        price: "50000",
        amount: "0.1",
        tif: "IOC",
        clientOrderId: "client-1"
      })
    ).rejects.toThrow(/missing order id/);
  });
});

