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

describe("cancelSyncJob", () => {
  it("cancels a running sync job", async () => {
    const mock = createKyselyMock<Namespace["main-db"]>();
    mock.enqueueResults(
      [baseSyncJob],
      [
        {
          ...baseSyncJob,
          status: "CANCELLED",
          finishedAt: new Date(),
          updatedAt: new Date(),
        },
      ],
    );

    const result = await mock.withTx((trx) => run(trx, { 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 mock = createKyselyMock<Namespace["main-db"]>();
    const running = {
      ...baseSyncJob,
      processedCount: 10,
      successCount: 8,
      errorCount: 2,
      errorSummary: "Timeout",
    };
    mock.enqueueResults(
      [running],
      [
        {
          ...running,
          status: "CANCELLED",
          finishedAt: new Date(),
          updatedAt: new Date(),
        },
      ],
    );

    const result = await mock.withTx((trx) => run(trx, { 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 mock = createKyselyMock<Namespace["main-db"]>();
    mock.enqueueResults([failedSyncJob]);

    const result = await mock.withTx((trx) =>
      run(trx, { syncJobId: failedSyncJob.id }, commandCtx),
    );

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