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

type OrderByField = "createdAt";

export interface ListApprovalRequestsForRequesterInput extends PaginationInput<OrderByField> {
  userId: string;
  status?: ApprovalRequestStatus;
}

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

  const rows = await db
    .selectFrom("ApprovalRequest")
    .selectAll()
    .where("requesterId", "=", input.userId)
    .where("status", "=", status)
    .orderBy(orderBy, orderDirection)
    .limit(limit + 1)
    .offset(offset)
    .execute();

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