import { describe, expect, it } from "vitest";
import { createMockDb } from "../../../testing/index";
import type { DB } from "../generated/kysely-tailordb";
import { CompanyScopeRequiredError } from "../lib/errors.generated";
import { baseChannel, baseCompany, baseSyncJob, failedSyncJob } from "../testing/fixtures";
import { expectErr, expectOk } from "../testing/commandTestUtils";
import { run } from "./listSyncJobs";

describe("listSyncJobs", () => {
  it("lists sync jobs by company", async () => {
    const { db, spies } = createMockDb<DB>();
    spies.select.mockReturnValueOnce([baseSyncJob, failedSyncJob]);

    const result = await run(db, { companyId: baseCompany.id });
    const { items } = expectOk<{ items: unknown[]; hasNextPage: boolean }>(result as never);

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

  it("filters sync jobs by channel and direction when provided", async () => {
    const { db, spies } = createMockDb<DB>();
    spies.select.mockReturnValueOnce([baseSyncJob]);

    const result = await run(db, {
      companyId: baseCompany.id,
      channelId: baseChannel.id,
      direction: "IMPORT",
    });
    const { items } = expectOk<{ items: unknown[]; hasNextPage: boolean }>(result as never);

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

  it("filters sync jobs by terminal status when provided", async () => {
    const { db, spies } = createMockDb<DB>();
    spies.select.mockReturnValueOnce([failedSyncJob]);

    const result = await run(db, { companyId: baseCompany.id, status: "FAILED" });
    const { items } = expectOk<{ items: unknown[]; hasNextPage: boolean }>(result as never);

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

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

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