import { describe, expect, it } from "vitest";
import { createMockDb } from "../../../testing/index";
import type { Transaction } from "../generated/kysely-tailordb";
import { ChannelNotSyncableError, SyncDirectionRequiredError } from "../lib/errors.generated";
import { baseChannel, baseSyncJob, inactiveChannel } from "../testing/fixtures";
import { commandCtx, expectErr, expectOk } from "../testing/commandTestUtils";
import { run } from "./startSyncJob";

describe("startSyncJob", () => {
  it("starts a running sync job for an active channel", async () => {
    const { db, spies } = createMockDb<Transaction>();
    spies.select.mockReturnValueOnce(baseChannel);
    spies.insert.mockReturnValueOnce(baseSyncJob);

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

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

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

    expectErr(result, ChannelNotSyncableError);
  });

  it("throws when direction is missing", async () => {
    const { db } = createMockDb<Transaction>();

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

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