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

describe("startSyncJob", () => {
  it("starts a running sync job for an active channel", async () => {
    const mock = createKyselyMock<Namespace["main-db"]>();
    mock.enqueueResults([baseChannel], [baseSyncJob]);

    const result = await mock.withTx((trx) =>
      run(
        trx,
        { companyId: baseChannel.companyId, channelId: baseChannel.id, direction: "IMPORT" },
        commandCtx,
      ),
    );

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

  it("initializes sync counts to zero", async () => {
    const mock = createKyselyMock<Namespace["main-db"]>();
    mock.enqueueResults([baseChannel], [baseSyncJob]);

    const result = await mock.withTx((trx) =>
      run(
        trx,
        { companyId: baseChannel.companyId, channelId: baseChannel.id, direction: "IMPORT" },
        commandCtx,
      ),
    );

    const value = expectOk(result);
    expect(value.syncJob.processedCount).toBe(0);
    expect(value.syncJob.errorCount).toBe(0);
  });

  it("throws when channel is inactive for new sync execution", async () => {
    const mock = createKyselyMock<Namespace["main-db"]>();
    mock.enqueueResults([inactiveChannel]);

    const result = await mock.withTx((trx) =>
      run(
        trx,
        {
          companyId: inactiveChannel.companyId,
          channelId: inactiveChannel.id,
          direction: "IMPORT",
        },
        commandCtx,
      ),
    );

    expectErr(result, ChannelNotSyncableError);
  });

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

    const result = await mock.withTx((trx) =>
      run(
        trx,
        { companyId: baseChannel.companyId, channelId: baseChannel.id, direction: "" },
        commandCtx,
      ),
    );

    expectErr(result, SyncDirectionRequiredError);
  });
});
