import { db, type TailorAnyDBField, type TailorAnyDBType } from "@tailor-platform/sdk";
import { defaultGqlPermission, defaultPermission } from "../../../shared/modelPermissions";
import { user as userStub } from "../lib/_db_deps";
import { approvalPolicy } from "./approvalPolicy";
import { approvalRequestLifecycle } from "./approvalRequest.lifecycle.generated";

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

export function createApprovalRequestType<const F extends Record<string, TailorAnyDBField>>(
  params: CreateApprovalRequestTypeParams<F>,
) {
  return db
    .type("ApprovalRequest", {
      name: db.string().description("Human-readable request label"),
      purpose: db.string().description("Action-shaped intent (e.g. PRODUCT_ACTIVATION)"),
      targetEntityType: db
        .string()
        .description("Polymorphic target type tag (free string, no FK enforcement)"),
      targetEntityId: db.uuid().description("Polymorphic target row id (no FK enforcement)"),
      requesterId: db
        .uuid()
        .relation({
          type: "n-1",
          toward: { type: params.userType },
          backward: "approvalRequestsRequested",
        })
        .description("Foreign key to User who originated the request"),
      sourcePolicyId: db
        .uuid({ optional: true })
        .relation({
          type: "n-1",
          toward: { type: approvalPolicy },
          backward: "requests",
        })
        .description("Source ApprovalPolicy snapshot reference; null in direct mode"),
      status: db
        .enum(approvalRequestLifecycle.states)
        .description("Lifecycle status: PENDING, APPROVED, REJECTED, CANCELLED, WITHDRAWN"),
      rejectionReason: db
        .string({ optional: true })
        .description("Reason copied from rejecting ApprovalDecision.comment"),
      resolvedAt: db
        .datetime({ optional: true })
        .description("Set when status reaches any terminal state"),
      ...((params.fields ?? {}) as F),
      ...db.fields.timestamps(),
    })
    .permission(defaultPermission)
    .gqlPermission(defaultGqlPermission);
}

export const approvalRequest = createApprovalRequestType({ userType: userStub });
