import { createKyselyMock } from "@tailor-platform/sdk/vitest";
import { describe, expect, it } from "vitest";
import type { Namespace } from "../generated/kysely-tailordb";
import { CompanyScopeRequiredError } from "../lib/errors.generated";
import { expectErr, expectOk } from "../testing/commandTestUtils";
import { baseChannel, baseCompany, baseSyncJob, failedSyncJob } from "../testing/fixtures";
import { run } from "./listSyncJobs";

describe("listSyncJobs", () => {
  it("lists sync jobs by company", async () => {
    const mock = createKyselyMock<Namespace["main-db"]>();
    mock.enqueueResults([baseSyncJob, failedSyncJob]);

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

    expect(items).toHaveLength(2);
    expect(mock.selects[0].parameters).toContain(baseCompany.id);
    expect(mock.selects[0].sql).toMatch(/"companyId"/);
    expect(mock.selects[0].sql).toMatch(/order by .*"startedAt" desc/i);
  });

  it("filters sync jobs by channel and direction when provided", async () => {
    const mock = createKyselyMock<Namespace["main-db"]>();
    mock.enqueueResults([baseSyncJob]);

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

    expect(items).toHaveLength(1);
    expect(mock.selects[0].parameters).toContain(baseChannel.id);
    expect(mock.selects[0].parameters).toContain("IMPORT");
    expect(mock.selects[0].sql).toMatch(/"channelId"/);
    expect(mock.selects[0].sql).toMatch(/"direction"/);
  });

  it("filters sync jobs by terminal status when provided", async () => {
    const mock = createKyselyMock<Namespace["main-db"]>();
    mock.enqueueResults([failedSyncJob]);

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

    expect(items).toHaveLength(1);
    expect(mock.selects[0].parameters).toContain("FAILED");
    expect(mock.selects[0].sql).toMatch(/"status"/);
  });

  it("throws when company scope is missing", async () => {
    const mock = createKyselyMock<Namespace["main-db"]>();

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