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

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

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