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

type OrderByField = "createdAt" | "shipmentDate" | "status";

export interface ListShipmentsBySalesOrderInput extends PaginationInput<OrderByField> {
  salesOrderId: string;
}

export async function run(db: ReadonlyDB<DB>, input: ListShipmentsBySalesOrderInput) {
  if (!input.salesOrderId) {
    return err(new SalesOrderIdRequiredError("shipments"));
  }
  const limit = input.limit ?? DEFAULT_PAGE_SIZE;
  const offset = input.offset ?? 0;
  const orderBy = input.orderBy ?? "shipmentDate";
  const orderDirection = input.orderDirection ?? "desc";

  const shipments = await db
    .selectFrom("Shipment")
    .selectAll()
    .where("salesOrderId", "=", input.salesOrderId)
    .orderBy(orderBy, orderDirection)
    .limit(limit + 1)
    .offset(offset)
    .execute();
  return ok(buildPaginatedResult(shipments, limit));
}
