import { ok, type ReadonlyDB } from "@tailor-platform/erp-kit/core";
import type { DB } from "../generated/kysely-tailordb";
import {
  getTransferOrderReceivingStatus,
  getTransferOrderShippingStatus,
} from "../internal/transferOrderProgress";

export interface GetTransferOrderInput {
  id: string;
}

export async function run(db: ReadonlyDB<DB>, input: GetTransferOrderInput) {
  const transferOrder = await db
    .selectFrom("TransferOrder")
    .selectAll()
    .where("id", "=", input.id)
    .executeTakeFirst();

  if (!transferOrder) {
    return ok({
      transferOrder: null,
      transferOrderLines: [],
      shippingStatus: "NOT_SHIPPED" as const,
      receivingStatus: "NOT_RECEIVED" as const,
    });
  }

  const transferOrderLines = await db
    .selectFrom("TransferOrderLine")
    .selectAll()
    .where("transferOrderId", "=", input.id)
    .execute();

  return ok({
    transferOrder,
    transferOrderLines,
    shippingStatus: getTransferOrderShippingStatus(transferOrderLines),
    receivingStatus: getTransferOrderReceivingStatus(transferOrderLines),
  });
}
