import {
  buildPaginatedResult,
  DEFAULT_PAGE_SIZE,
  err,
  ok,
  type PaginationInput,
  type ReadonlyDB,
} from "@tailor-platform/erp-kit/core";
import type { DB, Selectable } from "../generated/kysely-tailordb";
import { CompanyScopeRequiredError } from "../lib/errors.generated";

type SJ = Selectable<"SyncJob">;
type OrderByField = "createdAt" | "startedAt" | "status";

export type ListSyncJobsInput = Pick<SJ, "companyId"> &
  Partial<Pick<SJ, "channelId" | "direction" | "status">> &
  PaginationInput<OrderByField>;

export async function run(db: ReadonlyDB<DB>, input: ListSyncJobsInput) {
  if (!input.companyId) {
    return err(new CompanyScopeRequiredError("sync-jobs"));
  }
  const limit = input.limit ?? DEFAULT_PAGE_SIZE;
  const offset = input.offset ?? 0;
  const orderBy = input.orderBy ?? "startedAt";
  const orderDirection = input.orderDirection ?? "desc";

  let query = db.selectFrom("SyncJob").selectAll().where("companyId", "=", input.companyId);
  if (input.channelId) {
    query = query.where("channelId", "=", input.channelId);
  }
  if (input.direction) {
    query = query.where("direction", "=", input.direction);
  }
  if (input.status) {
    query = query.where("status", "=", input.status);
  }

  const syncJobs = await query
    .orderBy(orderBy, orderDirection)
    .limit(limit + 1)
    .offset(offset)
    .execute();
  return ok(buildPaginatedResult(syncJobs, limit));
}
