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

type OrderByField = "name";

export interface ListPartnersByRoleInput extends PaginationInput<OrderByField> {
  role: PartnerRoleRole;
  status?: BusinessPartnerStatus;
}

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

  let query = db
    .selectFrom("PartnerRole")
    .innerJoin("BusinessPartner", "BusinessPartner.id", "PartnerRole.partnerId")
    .selectAll("BusinessPartner")
    .where("PartnerRole.role", "=", input.role);

  if (input.status !== undefined) {
    query = query.where("BusinessPartner.status", "=", input.status);
  }

  const items = await query
    .orderBy(`BusinessPartner.${orderBy}`, orderDirection)
    .limit(limit + 1)
    .offset(offset)
    .execute();

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