import { defaultGqlPermission, defaultPermission } from "@tailor-platform/erp-kit/core";
import { db } from "@tailor-platform/sdk";
import { approvalRequest } from "./approvalRequest";
import { approvalStepLifecycle } from "./approvalStep.lifecycle.generated";

export function createApprovalStepType() {
  return db
    .type("ApprovalStep", {
      approvalRequestId: db
        .uuid()
        .relation({
          type: "n-1",
          toward: { type: approvalRequest },
          backward: "steps",
        })
        .description("Foreign key to parent ApprovalRequest"),
      stepOrder: db.int().description("1-based sequential position within the request"),
      name: db.string().description("Human-readable step label (snapshotted from policy)"),
      minimumApprovals: db.int().description("Quorum threshold (1 .. count(assignees))"),
      status: db
        .enum(approvalStepLifecycle.states)
        .description("Step status: PENDING, IN_PROGRESS, APPROVED, or REJECTED"),
      resolvedAt: db
        .datetime({ optional: true })
        .description("Set when status reaches APPROVED or REJECTED; null otherwise"),
      ...db.fields.timestamps(),
    })
    .indexes({
      fields: ["approvalRequestId", "stepOrder"],
      unique: true,
      name: "approval_step_order_unique_idx",
    })
    .permission(defaultPermission)
    .gqlPermission(defaultGqlPermission);
}

export const approvalStep = createApprovalStepType();
