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 { ChannelIdRequiredError } from "../lib/errors.generated";

type L = Selectable<"Listing">;
type OrderByField = "createdAt" | "status" | "externalIdentifier";

export type ListListingsByChannelInput = Pick<L, "channelId"> &
  Partial<Pick<L, "status">> &
  PaginationInput<OrderByField>;

export async function run(db: ReadonlyDB<DB>, input: ListListingsByChannelInput) {
  if (!input.channelId) {
    return err(new ChannelIdRequiredError("listing"));
  }
  const limit = input.limit ?? DEFAULT_PAGE_SIZE;
  const offset = input.offset ?? 0;
  const orderBy = input.orderBy ?? "createdAt";
  const orderDirection = input.orderDirection ?? "desc";

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

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