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

type OrderByField = "createdAt";

export interface ListContactPersonsByPartnerInput extends PaginationInput<OrderByField> {
  partnerId: string;
}

export async function run(db: ReadonlyDB<DB>, input: ListContactPersonsByPartnerInput) {
  const limit = input.limit ?? DEFAULT_PAGE_SIZE;
  const offset = input.offset ?? 0;
  const orderBy = input.orderBy ?? "createdAt";
  const orderDirection = input.orderDirection ?? "asc";

  const items = await db
    .selectFrom("ContactPerson")
    .selectAll()
    .where("partnerId", "=", input.partnerId)
    .orderBy(orderBy, orderDirection)
    .limit(limit + 1)
    .offset(offset)
    .execute();

  return ok(buildPaginatedResult(items, limit));
}
