import { createKyselyMock } from "@tailor-platform/sdk/vitest";
import { describe, expect, it } from "vitest";
import type { Namespace } from "../generated/kysely-tailordb";
import { expectOk } from "../testing/commandTestUtils";
import { baseSyncJob, failedSyncJob } from "../testing/fixtures";
import { run } from "./getSyncJob";

describe("getSyncJob", () => {
  it("returns sync job when found by id", async () => {
    const mock = createKyselyMock<Namespace["main-db"]>();
    mock.enqueueResults([baseSyncJob]);

    const result = await run(mock.db, { id: baseSyncJob.id });
    const { syncJob } = expectOk<{ syncJob: unknown }>(result as never);

    expect(syncJob).not.toBeNull();
    expect(syncJob).toMatchObject({ id: baseSyncJob.id });
  });

  it("returns failed sync job with counts and error summary", async () => {
    const mock = createKyselyMock<Namespace["main-db"]>();
    mock.enqueueResults([failedSyncJob]);

    const result = await run(mock.db, { id: failedSyncJob.id });
    const { syncJob } = expectOk<{
      syncJob: { status: string; errorCount: number; errorSummary: string };
    }>(result as never);

    expect(syncJob.status).toBe("FAILED");
    expect(syncJob.errorCount).toBe(1);
    expect(syncJob.errorSummary).toBe("Timeout");
  });

  it("returns null when sync job is not found", async () => {
    const mock = createKyselyMock<Namespace["main-db"]>();
    mock.enqueueResults([]);

    const result = await run(mock.db, { id: "nonexistent-id" });
    const { syncJob } = expectOk<{ syncJob: unknown }>(result as never);

    expect(syncJob).toBeNull();
  });
});
