import { err, ok, type ReadonlyDB } from "@tailor-platform/erp-kit/core";
import type { DB } from "../generated/kysely-tailordb";
import { InvariantViolationMultipleOpenError } from "../lib/errors.generated";

export interface GetActiveApprovalRequestInput {
  targetEntityType: string;
  targetEntityId: string;
}

export async function run(db: ReadonlyDB<DB>, input: GetActiveApprovalRequestInput) {
  const rows = await db
    .selectFrom("ApprovalRequest")
    .selectAll()
    .where("targetEntityType", "=", input.targetEntityType)
    .where("targetEntityId", "=", input.targetEntityId)
    .where("status", "in", ["PENDING", "REVISION_REQUESTED"])
    .execute();

  if (rows.length > 1) {
    return err(
      new InvariantViolationMultipleOpenError(`${input.targetEntityType}:${input.targetEntityId}`),
    );
  }

  return ok({ approvalRequest: rows[0] ?? null });
}
