import type { Transaction } from "../generated/kysely-tailordb";
import {
  ChannelNotFoundError,
  ChannelNotSyncableError,
  SyncDirectionRequiredError,
} from "../lib/errors.generated";
import { encodeJson } from "../lib/domain";
import { err, ok, type CommandContext } from "@tailor-platform/erp-kit/module";

export interface StartSyncJobInput {
  companyId: string;
  channelId: string;
  direction: string;
  context?: Record<string, unknown> | null;
}

export async function run(db: Transaction, input: StartSyncJobInput, ctx: CommandContext) {
  void ctx;
  if (!input.direction) {
    return err(new SyncDirectionRequiredError(input.channelId));
  }
  const channel = await db
    .selectFrom("Channel")
    .selectAll()
    .where("id", "=", input.channelId)
    .executeTakeFirst();
  if (!channel) {
    return err(new ChannelNotFoundError(input.channelId));
  }
  if (channel.status !== "ACTIVE") {
    return err(new ChannelNotSyncableError(input.channelId));
  }
  const syncJob = await db
    .insertInto("SyncJob")
    .values({
      companyId: input.companyId,
      channelId: input.channelId,
      direction: input.direction,
      status: "RUNNING",
      startedAt: new Date(),
      finishedAt: null,
      processedCount: 0,
      successCount: 0,
      errorCount: 0,
      errorSummary: null,
      retryOfSyncJobId: null,
      context: input.context ? encodeJson(input.context) : null,
      createdAt: new Date(),
      updatedAt: null,
    })
    .returningAll()
    .executeTakeFirst();
  return ok({ syncJob: syncJob! });
}
