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 ApprovalRequestOrderByField = "createdAt" | "resolvedAt";

export interface ListApprovalRequestsByTargetInput extends PaginationInput<ApprovalRequestOrderByField> {
  targetEntityType: string;
  targetEntityId: string;
  status?: ApprovalRequestStatus;
}

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

  let query = db
    .selectFrom("ApprovalRequest")
    .selectAll()
    .where("targetEntityType", "=", input.targetEntityType)
    .where("targetEntityId", "=", input.targetEntityId);
  if (input.status) query = query.where("status", "=", input.status);

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

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