import { ok, type ReadonlyDB } from "@tailor-platform/erp-kit/core";
import type { DB } from "../generated/kysely-tailordb";
import { decodeJson } from "../lib/domain";

export interface GetChannelOrderInput {
  id: string;
}

export async function run(db: ReadonlyDB<DB>, input: GetChannelOrderInput) {
  const channelOrder = await db
    .selectFrom("ChannelOrder")
    .selectAll()
    .where("id", "=", input.id)
    .executeTakeFirst();
  if (!channelOrder) {
    return ok({ channelOrder: null });
  }
  return ok({
    channelOrder: {
      ...channelOrder,
      rawPayload: decodeJson<Record<string, unknown> | null>(channelOrder.rawPayload, null),
      normalizedPayload: decodeJson<Record<string, unknown> | null>(
        channelOrder.normalizedPayload,
        null,
      ),
      retryContext: decodeJson<Record<string, unknown> | null>(channelOrder.retryContext, null),
    },
  });
}
