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

type OrderByField = "name";

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

export async function run(db: ReadonlyDB<DB>, input: ListPartnersByRoleInput) {
  if (input.role !== "CUSTOMER" && input.role !== "SUPPLIER") {
    return err(new InvalidRoleError(input.role));
  }

  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 as PartnerRoleRole);

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

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

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