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

export interface GetApprovalDecisionHistoryInput {
  approvalRequestId: string;
}

export async function run(db: ReadonlyDB<DB>, input: GetApprovalDecisionHistoryInput) {
  const request = await db
    .selectFrom("ApprovalRequest")
    .selectAll()
    .where("id", "=", input.approvalRequestId)
    .executeTakeFirst();
  if (!request) return err(new RequestNotFoundError(input.approvalRequestId));

  const decisions = await db
    .selectFrom("ApprovalDecision")
    .selectAll()
    .where("approvalRequestId", "=", input.approvalRequestId)
    .orderBy("decidedAt", "asc")
    .execute();

  return ok({ approvalDecisions: decisions });
}
