import { describe, expect, it } from "vitest";
import { createMockDb } from "../../../testing/index";
import type { DB } from "../generated/kysely-tailordb";
import { baseSyncJob, failedSyncJob } from "../testing/fixtures";
import { expectOk } from "../testing/commandTestUtils";
import { run } from "./getSyncJob";

describe("getSyncJob", () => {
  it("returns sync job when found by id", async () => {
    const { db, spies } = createMockDb<DB>();
    spies.select.mockReturnValueOnce(baseSyncJob);

    const result = await run(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 { db, spies } = createMockDb<DB>();
    spies.select.mockReturnValueOnce(failedSyncJob);

    const result = await run(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 { db, spies } = createMockDb<DB>();
    spies.select.mockReturnValueOnce(undefined);

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

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