import { describe, expect, it } from "vitest";
import { createMockDb } from "../../../testing/index";
import type { DB } from "../generated/kysely-tailordb";
import { SiteScopeRequiredError } from "../lib/errors.generated";
import { baseActiveWorkCenter, baseDraftWorkCenter } from "../testing/fixtures";
import { expectOk, expectErr } from "../testing/commandTestUtils";
import { run } from "./listWorkCentersBySite";

describe("listWorkCentersBySite", () => {
  it("lists work centers for a site", async () => {
    const { db, spies } = createMockDb<DB>();
    spies.select.mockReturnValueOnce([baseActiveWorkCenter, baseDraftWorkCenter]);

    const result = await run(db, {
      companyId: "company-1",
      siteId: "site-1",
    });
    const { items } = expectOk<{ items: unknown[]; hasNextPage: boolean }>(result as never);

    expect(items).toHaveLength(2);
  });

  it("filters work centers by status when provided", async () => {
    const { db, spies } = createMockDb<DB>();
    spies.select.mockReturnValueOnce([baseActiveWorkCenter]);

    const result = await run(db, {
      companyId: "company-1",
      siteId: "site-1",
      status: "ACTIVE",
    });
    const { items } = expectOk<{ items: unknown[]; hasNextPage: boolean }>(result as never);

    expect(items).toHaveLength(1);
  });

  it("filters work centers by work-center type and accepts name ordering", async () => {
    const { db, spies } = createMockDb<DB>();
    spies.select.mockReturnValueOnce([{ ...baseActiveWorkCenter, name: "Assembly Cell A" }]);

    const result = await run(db, {
      companyId: "company-1",
      siteId: "site-1",
      workCenterType: "ASSEMBLY",
      orderBy: "name",
    });
    const { items } = expectOk<{ items: { code: string }[]; hasNextPage: boolean }>(
      result as never,
    );

    expect(items).toHaveLength(1);
    expect(items[0].code).toBe(baseActiveWorkCenter.code);
  });

  it("returns an empty list when the site has no work centers", async () => {
    const { db, spies } = createMockDb<DB>();
    spies.select.mockReturnValueOnce([]);

    const result = await run(db, {
      companyId: "company-1",
      siteId: "site-1",
    });
    const { items } = expectOk<{ items: unknown[]; hasNextPage: boolean }>(result as never);

    expect(items).toHaveLength(0);
  });

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

    const result = await run(db, { companyId: "", siteId: "site-1" });
    expectErr(result as never, SiteScopeRequiredError);
  });

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

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