import type { DeveloperAccessStatus } from "../../lib/devApi";
import {
  hasDeveloperAccessForPages,
  isDeveloperRequestPendingForPages,
} from "../developer-access/developerAccessPages";

export type ClientCreateAccessState =
  | "can_create"
  | "pending"
  | "request_required"
  | "forbidden";

type ResolveClientCreateAccessParams = {
  role: string;
  accessStatus?: DeveloperAccessStatus;
};

function canSelfRequestDeveloperAccess(role: string) {
  return role === "user";
}

export function resolveClientCreateAccess({
  role,
  accessStatus,
}: ResolveClientCreateAccessParams): ClientCreateAccessState {
  if (!role.trim()) {
    return "request_required";
  }

  if (!canSelfRequestDeveloperAccess(role)) {
    return "can_create";
  }

  if (
    hasDeveloperAccessForPages(accessStatus?.approvedPages, ["client_create"])
  ) {
    return "can_create";
  }

  if (
    isDeveloperRequestPendingForPages(accessStatus?.pendingPages, [
      "client_create",
    ])
  ) {
    return "pending";
  }

  return "request_required";
}
