import { describe, expect, it } from "vitest";
import { createMockDb } from "../../../testing/index";
import type { Transaction } from "../generated/kysely-tailordb";
import { InvalidSyncJobStatusError } from "../lib/errors.generated";
import { baseSyncJob, failedSyncJob } from "../testing/fixtures";
import { commandCtx, expectErr, expectOk } from "../testing/commandTestUtils";
import { run } from "./cancelSyncJob";

describe("cancelSyncJob", () => {
  it("cancels a running sync job", async () => {
    const { db, spies } = createMockDb<Transaction>();
    spies.select.mockReturnValueOnce(baseSyncJob);
    spies.update.mockReturnValueOnce({
      ...baseSyncJob,
      status: "CANCELLED",
      finishedAt: new Date(),
      updatedAt: new Date(),
    });

    const result = await run(db, { syncJobId: baseSyncJob.id }, commandCtx);

    const value = expectOk(result);
    expect(value.syncJob.status).toBe("CANCELLED");
  });

  it("preserves existing counts and error context when cancelled", async () => {
    const { db, spies } = createMockDb<Transaction>();
    const running = {
      ...baseSyncJob,
      processedCount: 10,
      successCount: 8,
      errorCount: 2,
      errorSummary: "Timeout",
    };
    spies.select.mockReturnValueOnce(running);
    spies.update.mockReturnValueOnce({
      ...running,
      status: "CANCELLED",
      finishedAt: new Date(),
      updatedAt: new Date(),
    });

    const result = await run(db, { syncJobId: running.id }, commandCtx);

    const value = expectOk(result);
    expect(value.syncJob.processedCount).toBe(10);
    expect(value.syncJob.errorSummary).toBe("Timeout");
  });

  it("throws when sync job is not running", async () => {
    const { db, spies } = createMockDb<Transaction>();
    spies.select.mockReturnValueOnce(failedSyncJob);

    const result = await run(db, { syncJobId: failedSyncJob.id }, commandCtx);

    expectErr(result, InvalidSyncJobStatusError);
  });
});
