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 ListApprovalRequestsForApproverInput extends PaginationInput<OrderByField> {
  userId: string;
  status?: ApprovalRequestStatus;
}

export async function run(db: ReadonlyDB<DB>, input: ListApprovalRequestsForApproverInput) {
  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 ?? "PENDING";

  // TODO: collapse into a single paginated query once TailorDB supports DISTINCT or subqueries
  const candidateRows = await db
    .selectFrom("ApprovalStep")
    .innerJoin("ApprovalStepAssignee", "ApprovalStepAssignee.approvalStepId", "ApprovalStep.id")
    .select("ApprovalStep.approvalRequestId")
    .where("ApprovalStepAssignee.userId", "=", input.userId)
    .where("ApprovalStepAssignee.status", "=", "PENDING")
    .where("ApprovalStep.status", "=", "IN_PROGRESS")
    .execute();

  const requestIds = [...new Set(candidateRows.map((r) => r.approvalRequestId))];
  if (requestIds.length === 0) {
    return ok(buildPaginatedResult([], limit));
  }

  const rows = await db
    .selectFrom("ApprovalRequest")
    .selectAll()
    .where("id", "in", requestIds)
    .where("status", "=", status)
    .orderBy(orderBy, orderDirection)
    .limit(limit + 1)
    .offset(offset)
    .execute();

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