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

type ApprovalPolicyOrderByField = "purpose" | "name" | "activatedAt" | "createdAt";

export interface ListApprovalPoliciesInput extends PaginationInput<ApprovalPolicyOrderByField> {
  purpose?: string;
  status?: ApprovalPolicyStatus;
}

export async function run(db: ReadonlyDB<DB>, input: ListApprovalPoliciesInput) {
  const limit = input.limit ?? DEFAULT_PAGE_SIZE;
  const offset = input.offset ?? 0;

  let query = db.selectFrom("ApprovalPolicy").selectAll();

  if (input.purpose) {
    query = query.where("purpose", "=", input.purpose);
  }
  if (input.status) {
    query = query.where("status", "=", input.status);
  }

  if (input.orderBy) {
    query = query.orderBy(input.orderBy, input.orderDirection ?? "asc");
  } else {
    query = query.orderBy("purpose", "asc").orderBy("name", "asc").orderBy("activatedAt", "desc");
  }

  const rows = await query
    .limit(limit + 1)
    .offset(offset)
    .execute();

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