import { defaultGqlPermission, defaultPermission } from "@tailor-platform/erp-kit/core";
import { db, type TailorAnyDBType } from "@tailor-platform/sdk";
import { approvalPolicyStep } from "./approvalPolicyStep";

const ROLE_QUORUM_TYPES = ["ALL", "ANY"] as const;

export interface CreateApprovalPolicyStepAssigneeTypeParams {
  userType?: TailorAnyDBType;
  roleType?: TailorAnyDBType;
}

export function createApprovalPolicyStepAssigneeType(
  params: CreateApprovalPolicyStepAssigneeTypeParams,
) {
  const userId = db
    .uuid({ optional: true })
    .description("Specific user assignee (XOR with roleId)");
  const roleId = db
    .uuid({ optional: true })
    .description("Role assignee, expanded to current ACTIVE members at runtime (XOR with userId)");
  return db
    .type("ApprovalPolicyStepAssignee", {
      approvalPolicyStepId: db
        .uuid()
        .relation({
          type: "n-1",
          toward: { type: approvalPolicyStep },
          backward: "assignees",
        })
        .description("Foreign key to ApprovalPolicyStep"),
      userId: params.userType
        ? userId.relation({
            type: "n-1",
            toward: { type: params.userType },
            backward: "approvalPolicyStepAssignees",
          })
        : userId,
      roleId: params.roleType
        ? roleId.relation({
            type: "n-1",
            toward: { type: params.roleType },
            backward: "approvalPolicyStepAssignees",
          })
        : roleId,
      required: db
        .bool()
        .description(
          "User-assignee mandatory flag (meaningful only when userId is set, ignored on role assignees)",
        ),
      roleQuorum: db
        .enum(ROLE_QUORUM_TYPES, { optional: true })
        .description(
          "Role-assignee group semantics (meaningful only when roleId is set): ALL = every member must approve, ANY = a single member's approval suffices, null = no group-level constraint (only step.minimumApprovals applies)",
        ),
      ...db.fields.timestamps(),
    })
    .permission(defaultPermission)
    .gqlPermission(defaultGqlPermission);
}

export const approvalPolicyStepAssignee = createApprovalPolicyStepAssigneeType({});
