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

type RoleOrderByField = "name" | "createdAt";

export interface ListRolesInput extends PaginationInput<RoleOrderByField> {
  status?: RoleStatus;
}

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

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

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

  const roles = await query
    .orderBy(orderBy, orderDirection)
    .limit(limit + 1)
    .offset(offset)
    .execute();

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