import type { Logger } from "nestjs-pino";
import type { ConfigService } from "@nestjs/config";
import { SalesforceConnection } from "./salesforce-connection.service";
import type { SalesforceRequestQueueService } from "@bff/core/queue/services/salesforce-request-queue.service";

describe("SalesforceConnection", () => {
  const createService = () => {
    const configService = {
      get: jest.fn(),
    } as unknown as ConfigService;

    const execute = jest.fn<
      Promise<unknown>,
      [fn: () => Promise<unknown>, options?: Record<string, unknown>]
    >(async (fn): Promise<unknown> => {
      return await fn();
    });

    const executeHighPriority = jest.fn<
      Promise<unknown>,
      [fn: () => Promise<unknown>, options?: Record<string, unknown>]
    >(async (fn): Promise<unknown> => {
      return await fn();
    });

    const requestQueue = {
      execute,
      executeHighPriority,
    } as unknown as SalesforceRequestQueueService;

    const logger = {
      debug: jest.fn(),
      warn: jest.fn(),
      error: jest.fn(),
      log: jest.fn(),
    } as unknown as Logger;

    const service = new SalesforceConnection(configService, requestQueue, logger);

    // Override internal connection with simple stubs
    const queryMock = jest.fn().mockResolvedValue("query-result");
    service["connection"] = {
      query: queryMock,
      sobject: jest.fn().mockReturnValue({
        create: jest.fn().mockResolvedValue({ id: "001" }),
        update: jest.fn().mockResolvedValue({}),
      }),
    } as unknown as (typeof service)["connection"];

    jest
      .spyOn(service as unknown as { ensureConnected(): Promise<void> }, "ensureConnected")
      .mockResolvedValue();

    return {
      service,
      requestQueue,
      queryMock,
      execute,
      executeHighPriority,
    };
  };

  afterEach(() => {
    jest.restoreAllMocks();
  });

  it("routes standard queries through the request queue with derived priority metadata", async () => {
    const { service, execute, queryMock } = createService();

    await service.query("SELECT Id FROM Account WHERE Id = '001'");

    expect(execute).toHaveBeenCalledTimes(1);
    const [, options] = execute.mock.calls[0];
    expect(options).toMatchObject({
      priority: 8,
      isLongRunning: false,
      label: "salesforce:query:account",
    });
    expect(queryMock).toHaveBeenCalledTimes(1);
  });

  it("routes SObject create operations through the high-priority queue", async () => {
    const { service, executeHighPriority } = createService();

    const sobject = service.sobject("Order");
    await sobject.create({ Name: "Test" });

    expect(executeHighPriority).toHaveBeenCalledTimes(1);
    const [, options] = executeHighPriority.mock.calls[0];
    expect(options).toMatchObject({ label: "salesforce:sobject:Order:create" });
  });
});
