import { describe, expect, it } from "vitest";
import { createMockDb } from "../../../testing/index";
import type { DB } from "../generated/kysely-tailordb";
import {
  baseDraftRouting,
  baseActiveRouting,
  baseInactiveRouting,
  baseRoutingOperation,
  baseRoutingOperation2,
} from "../testing/fixtures";
import { expectOk, expectErr } from "../testing/commandTestUtils";
import { RoutingNotFoundError, CompanyScopeRequiredError } from "../lib/errors.generated";
import { run } from "./getRouting";

describe("getRouting", () => {
  it("returns a routing with ordered operations when found", async () => {
    const { db, spies } = createMockDb<DB>();
    spies.select.mockReturnValueOnce(baseActiveRouting);
    spies.select.mockReturnValueOnce([baseRoutingOperation, baseRoutingOperation2]);

    const result = await run(db, { id: baseActiveRouting.id, companyId: "company-1" });
    const { routing, operations } = expectOk<{
      routing: unknown;
      operations: unknown[];
    }>(result as never);

    expect(routing).toMatchObject({ id: baseActiveRouting.id });
    expect(operations).toHaveLength(2);
  });

  it("returns inactive routing revisions when requested", async () => {
    const { db, spies } = createMockDb<DB>();
    spies.select.mockReturnValueOnce(baseInactiveRouting);
    spies.select.mockReturnValueOnce([]);

    const result = await run(db, { id: baseInactiveRouting.id, companyId: "company-1" });
    const { routing } = expectOk<{
      routing: { status: string };
    }>(result as never);

    expect(routing.status).toBe("INACTIVE");
  });

  it("returns routing data for the requested company scope", async () => {
    const { db, spies } = createMockDb<DB>();
    spies.select.mockReturnValueOnce(baseDraftRouting);
    spies.select.mockReturnValueOnce([baseRoutingOperation]);

    const result = await run(db, { id: baseDraftRouting.id, companyId: "company-1" });
    const { routing } = expectOk<{
      routing: { companyId: string };
    }>(result as never);

    expect(routing.companyId).toBe("company-1");
  });

  it("returns error when the routing does not exist", async () => {
    const { db, spies } = createMockDb<DB>();
    spies.select.mockReturnValueOnce(undefined);

    const result = await run(db, { id: "nonexistent-id", companyId: "company-1" });
    expectErr(result as never, RoutingNotFoundError);
  });

  it("returns error when company scope is not provided", async () => {
    const { db } = createMockDb<DB>();

    const result = await run(db, { id: "routing-1", companyId: "" });
    expectErr(result as never, CompanyScopeRequiredError);
  });
});
