import { db, type TailorAnyDBField } from "@tailor-platform/sdk";
import { defaultGqlPermission, defaultPermission } from "../../../shared/modelPermissions";
import { approvalRequest } from "./approvalRequest";
import { approvalStepLifecycle } from "./approvalStep.lifecycle.generated";

export interface CreateApprovalStepTypeParams<F extends Record<string, TailorAnyDBField>> {
  fields?: F;
}

export function createApprovalStepType<const F extends Record<string, TailorAnyDBField>>(
  params: CreateApprovalStepTypeParams<F>,
) {
  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"),
      ...((params.fields ?? {}) as F),
      ...db.fields.timestamps(),
    })
    .indexes({
      fields: ["approvalRequestId", "stepOrder"],
      unique: true,
      name: "approval_step_order_unique_idx",
    })
    .permission(defaultPermission)
    .gqlPermission(defaultGqlPermission);
}

export const approvalStep = createApprovalStepType({});
