import { importShared } from './__federation_fn_import-BLFDCY-V.js';
import { j as jsxRuntimeExports } from './jsx-runtime-XI9uIe3W.js';
import { a, A as AuthConfigTabs } from './styles-tkrWV-ZE.js';
import { c as createAuthRoleSchema, a as createAuthPluginDefinitionSchema, b as createDefaultAuthRoles } from './plugin-definition-DJzXScRp.js';
import { c as useFieldArray$1, a as useForm, d as useWatch } from './index.esm-BraHxHLB.js';
import { o as MdEdit, p as MdDeleteOutline, q as MdAdd } from './index-B_A3cgiy.js';

// src/rhf/useFieldArray.ts
const {useMemo: useMemo$1} = await importShared('react');
function useFieldArray(props) {
  const original = useFieldArray$1(props);
  const newFields = useMemo$1(() => {
    if (!props.getTransformer) {
      return original.fields;
    }
    return original.fields.map(props.getTransformer);
  }, [original.fields, props.getTransformer]);
  return {
    fields: newFields,
    move: original.move,
    remove: original.remove,
    swap: original.swap,
    prepend: (value, options) => {
      if (!props.setTransformer) {
        return original.prepend(value, options);
      }
      const newValue = Array.isArray(value) ? value.map(props.setTransformer) : props.setTransformer(value);
      original.prepend(newValue, options);
    },
    append: (value, options) => {
      if (!props.setTransformer) {
        return original.append(value, options);
      }
      const newValue = Array.isArray(value) ? value.map(props.setTransformer) : props.setTransformer(value);
      original.append(newValue, options);
    },
    insert: (index, value, options) => {
      if (!props.setTransformer) {
        return original.insert(index, value, options);
      }
      const newValue = Array.isArray(value) ? value.map(props.setTransformer) : props.setTransformer(value);
      original.insert(index, newValue, options);
    },
    update: (index, value) => {
      if (!props.setTransformer) {
        return original.update(index, value);
      }
      const newValue = props.setTransformer(value);
      original.update(index, newValue);
    },
    replace: (value) => {
      if (!props.setTransformer) {
        return original.replace(value);
      }
      const newValue = props.setTransformer(value);
      original.replace(newValue);
    }
  };
}

const {useDefinitionSchema: useDefinitionSchema$1} = await importShared('@baseplate-dev/project-builder-lib/web');

const {Button: Button$1,Dialog,DialogContent,DialogDescription,DialogFooter,DialogHeader,DialogTitle,DialogTrigger,InputFieldController} = await importShared('@baseplate-dev/ui-components');
const {useId} = await importShared('react');
function RoleDialog({
  open,
  onOpenChange,
  role,
  isNew = false,
  onSave,
  asChild,
  children
}) {
  const authRoleSchema = useDefinitionSchema$1(createAuthRoleSchema);
  const form = useForm({
    resolver: a(authRoleSchema),
    values: role
  });
  const { control, handleSubmit } = form;
  const onSubmit = handleSubmit((data) => {
    onSave(data);
    onOpenChange?.(false);
  });
  const formId = useId();
  return /* @__PURE__ */ jsxRuntimeExports.jsxs(Dialog, { open, onOpenChange, children: [
    /* @__PURE__ */ jsxRuntimeExports.jsx(DialogTrigger, { asChild, children }),
    /* @__PURE__ */ jsxRuntimeExports.jsx(DialogContent, { children: /* @__PURE__ */ jsxRuntimeExports.jsxs(
      "form",
      {
        id: formId,
        onSubmit: (e) => {
          e.stopPropagation();
          return onSubmit(e);
        },
        children: [
          /* @__PURE__ */ jsxRuntimeExports.jsxs(DialogHeader, { children: [
            /* @__PURE__ */ jsxRuntimeExports.jsx(DialogTitle, { children: isNew ? "Add Role" : "Edit Role" }),
            /* @__PURE__ */ jsxRuntimeExports.jsx(DialogDescription, { children: isNew ? "Enter the details for the new role." : "Update the role details below." })
          ] }),
          /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "auth:space-y-4 auth:py-4", children: [
            /* @__PURE__ */ jsxRuntimeExports.jsx(
              InputFieldController,
              {
                label: "Role Name",
                name: "name",
                control,
                placeholder: "Enter role name"
              }
            ),
            /* @__PURE__ */ jsxRuntimeExports.jsx(
              InputFieldController,
              {
                label: "Description",
                name: "comment",
                control,
                placeholder: "Describe this role's purpose"
              }
            )
          ] }),
          /* @__PURE__ */ jsxRuntimeExports.jsxs(DialogFooter, { children: [
            /* @__PURE__ */ jsxRuntimeExports.jsx(
              Button$1,
              {
                type: "button",
                variant: "outline",
                onClick: () => {
                  onOpenChange?.(false);
                },
                children: "Cancel"
              }
            ),
            /* @__PURE__ */ jsxRuntimeExports.jsxs(Button$1, { form: formId, type: "submit", children: [
              isNew ? "Add" : "Update",
              " Role"
            ] })
          ] })
        ]
      }
    ) })
  ] });
}

const {authRoleEntityType} = await importShared('@baseplate-dev/project-builder-lib');

const {Badge,Button,RecordView,RecordViewActions,RecordViewItem,RecordViewItemList,SectionListSection: SectionListSection$1,SectionListSectionContent: SectionListSectionContent$1,SectionListSectionDescription: SectionListSectionDescription$1,SectionListSectionHeader: SectionListSectionHeader$1,SectionListSectionTitle: SectionListSectionTitle$1,useConfirmDialog} = await importShared('@baseplate-dev/ui-components');
const {useState} = await importShared('react');
function RoleEditorForm({
  className,
  control
}) {
  const { requestConfirm } = useConfirmDialog();
  const { append, update, remove } = useFieldArray({
    control,
    name: "roles"
  });
  const [roleToEdit, setRoleToEdit] = useState();
  const [isEditing, setIsEditing] = useState(false);
  const roles = useWatch({ control, name: "roles" });
  function handleSaveRole(newRole) {
    const existingIndex = roles.findIndex((role) => role.id === newRole.id);
    if (existingIndex === -1) {
      append(newRole);
    } else {
      update(existingIndex, newRole);
    }
  }
  function handleDeleteRole(roleIdx) {
    const role = roles[roleIdx];
    requestConfirm({
      title: "Delete Role",
      content: `Are you sure you want to delete the role "${role.name}"?`,
      onConfirm: () => {
        remove(roleIdx);
      }
    });
  }
  return /* @__PURE__ */ jsxRuntimeExports.jsxs(SectionListSection$1, { className, children: [
    /* @__PURE__ */ jsxRuntimeExports.jsxs(SectionListSectionHeader$1, { children: [
      /* @__PURE__ */ jsxRuntimeExports.jsx(SectionListSectionTitle$1, { children: "User Roles" }),
      /* @__PURE__ */ jsxRuntimeExports.jsx(SectionListSectionDescription$1, { children: "Define roles for your application. Default roles are protected and cannot be removed." })
    ] }),
    /* @__PURE__ */ jsxRuntimeExports.jsxs(SectionListSectionContent$1, { className: "auth:space-y-4", children: [
      roles.map((role, roleIdx) => /* @__PURE__ */ jsxRuntimeExports.jsxs(RecordView, { children: [
        /* @__PURE__ */ jsxRuntimeExports.jsxs(RecordViewItemList, { children: [
          /* @__PURE__ */ jsxRuntimeExports.jsx(RecordViewItem, { title: "Name", children: /* @__PURE__ */ jsxRuntimeExports.jsx("div", { className: "auth:flex auth:items-center auth:gap-2", children: /* @__PURE__ */ jsxRuntimeExports.jsx("span", { children: role.name }) }) }),
          /* @__PURE__ */ jsxRuntimeExports.jsx(RecordViewItem, { title: "Description", children: role.comment.trim() || /* @__PURE__ */ jsxRuntimeExports.jsx("span", { className: "auth:text-muted-foreground", children: "No description" }) })
        ] }),
        /* @__PURE__ */ jsxRuntimeExports.jsxs(RecordViewActions, { children: [
          role.builtIn && /* @__PURE__ */ jsxRuntimeExports.jsx(Badge, { variant: "secondary", children: "Default Role" }),
          !role.builtIn && /* @__PURE__ */ jsxRuntimeExports.jsxs(jsxRuntimeExports.Fragment, { children: [
            /* @__PURE__ */ jsxRuntimeExports.jsx(
              Button,
              {
                variant: "ghost",
                size: "icon",
                title: "Edit",
                "aria-label": "Edit role",
                onClick: () => {
                  setRoleToEdit(role);
                  setIsEditing(true);
                },
                children: /* @__PURE__ */ jsxRuntimeExports.jsx(MdEdit, {})
              }
            ),
            /* @__PURE__ */ jsxRuntimeExports.jsx(
              Button,
              {
                variant: "ghostDestructive",
                size: "icon",
                title: "Delete",
                "aria-label": "Delete role",
                onClick: () => {
                  handleDeleteRole(roleIdx);
                },
                children: /* @__PURE__ */ jsxRuntimeExports.jsx(MdDeleteOutline, {})
              }
            )
          ] })
        ] })
      ] }, role.id)),
      /* @__PURE__ */ jsxRuntimeExports.jsx(
        RoleDialog,
        {
          open: isEditing,
          onOpenChange: setIsEditing,
          role: roleToEdit,
          isNew: roleToEdit ? !roles.some((r) => r.id === roleToEdit.id) : true,
          onSave: handleSaveRole
        }
      ),
      /* @__PURE__ */ jsxRuntimeExports.jsxs(
        Button,
        {
          variant: "secondary",
          size: "sm",
          onClick: () => {
            setRoleToEdit({
              id: authRoleEntityType.generateNewId(),
              name: "",
              comment: "",
              builtIn: false
            });
            setIsEditing(true);
          },
          children: [
            /* @__PURE__ */ jsxRuntimeExports.jsx(MdAdd, {}),
            "Add Role"
          ]
        }
      )
    ] })
  ] });
}

const {FeatureUtils,getManagedPluginsForPlugin,PluginUtils} = await importShared('@baseplate-dev/project-builder-lib');

const {FeatureComboboxFieldController,useBlockUnsavedChangesNavigate,useDefinitionSchema,useProjectDefinition,useResettableForm} = await importShared('@baseplate-dev/project-builder-lib/web');

const {Alert,AlertDescription,AlertTitle,FormActionBar,SectionList,SectionListSection,SectionListSectionContent,SectionListSectionDescription,SectionListSectionHeader,SectionListSectionTitle,SelectFieldController} = await importShared('@baseplate-dev/ui-components');
const {Link,useNavigate} = await importShared('@tanstack/react-router');

const {useMemo} = await importShared('react');
function AuthDefinitionEditor({
  definition: pluginMetadata,
  metadata,
  onSave
}) {
  const {
    definition,
    definitionContainer,
    schemaParserContext,
    saveDefinitionWithFeedback
  } = useProjectDefinition();
  const authPluginDefinitionSchema = useDefinitionSchema(
    createAuthPluginDefinitionSchema
  );
  const availableImplementations = getManagedPluginsForPlugin(
    schemaParserContext.pluginStore,
    metadata.key
  );
  const defaultImplementation = availableImplementations.find(
    (i) => i.fullyQualifiedName === "@baseplate-dev/plugin-auth:local-auth"
  ) ?? availableImplementations[0];
  const defaultValues = useMemo(() => {
    if (pluginMetadata?.config) {
      return pluginMetadata.config;
    }
    const defaultAuthFeatureRef = FeatureUtils.getFeatureIdByNameOrDefault(
      definition,
      "auth"
    );
    return {
      implementationPluginKey: defaultImplementation.key,
      authFeatureRef: defaultAuthFeatureRef,
      roles: createDefaultAuthRoles()
    };
  }, [definition, pluginMetadata?.config, defaultImplementation]);
  const form = useResettableForm({
    resolver: a(authPluginDefinitionSchema),
    defaultValues
  });
  const { control, reset, handleSubmit, watch } = form;
  const implementationPluginKey = watch("implementationPluginKey");
  const selectedPlugin = implementationPluginKey && availableImplementations.find((i) => i.key === implementationPluginKey);
  const isSelectedImplementationActive = !!PluginUtils.byKey(
    definitionContainer.definition,
    implementationPluginKey
  );
  const hasSelectedImplementationChanged = implementationPluginKey !== pluginMetadata?.config?.implementationPluginKey;
  const selectedImplementationUrl = selectedPlugin ? `/plugins/edit/${selectedPlugin.key}` : void 0;
  const navigate = useNavigate();
  const onSubmit = handleSubmit(
    (data) => saveDefinitionWithFeedback(
      (draftConfig) => {
        const featureRef = FeatureUtils.ensureFeatureByNameRecursively(
          draftConfig,
          data.authFeatureRef
        );
        PluginUtils.setPluginConfig(
          draftConfig,
          metadata,
          {
            ...data,
            authFeatureRef: featureRef
          },
          definitionContainer
        );
        const otherPlugins = availableImplementations.filter(
          (i) => i.key !== implementationPluginKey
        );
        for (const plugin of otherPlugins) {
          PluginUtils.disablePlugin(
            draftConfig,
            plugin.key,
            definitionContainer.parserContext
          );
        }
      },
      {
        successMessage: `Successfully saved auth plugin! ${selectedImplementationUrl && !isSelectedImplementationActive ? `Please configure the provider plugin before syncing.` : ""}`,
        onSuccess: () => {
          onSave();
          if (selectedImplementationUrl && !isSelectedImplementationActive) {
            setTimeout(() => {
              navigate({ to: selectedImplementationUrl });
            }, 100);
          }
        }
      }
    )
  );
  useBlockUnsavedChangesNavigate({ control, reset, onSubmit });
  return /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "auth:relative auth:flex auth:h-full auth:flex-1 auth:flex-col auth:gap-4 auth:overflow-hidden", children: [
    /* @__PURE__ */ jsxRuntimeExports.jsx(AuthConfigTabs, {}),
    /* @__PURE__ */ jsxRuntimeExports.jsx(
      "div",
      {
        className: "auth:mb-[--action-bar-height] auth:flex auth:flex-1 auth:overflow-y-auto",
        style: {
          "--action-bar-height": "52px"
        },
        children: /* @__PURE__ */ jsxRuntimeExports.jsxs("form", { onSubmit, className: "auth:max-w-6xl auth:flex-1", children: [
          /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "auth:pb-16", children: [
            !isSelectedImplementationActive && selectedPlugin && !hasSelectedImplementationChanged && /* @__PURE__ */ jsxRuntimeExports.jsxs(Alert, { variant: "warning", children: [
              /* @__PURE__ */ jsxRuntimeExports.jsx(AlertTitle, { children: "Implementation Provider Not Active" }),
              /* @__PURE__ */ jsxRuntimeExports.jsx(AlertDescription, { children: /* @__PURE__ */ jsxRuntimeExports.jsxs("p", { children: [
                "The selected implementation provider is not active. Please make sure",
                " ",
                /* @__PURE__ */ jsxRuntimeExports.jsx(
                  Link,
                  {
                    to: selectedImplementationUrl,
                    className: "auth:inline-block auth:font-medium",
                    children: "configure the provider"
                  }
                ),
                " ",
                "before syncing."
              ] }) })
            ] }),
            /* @__PURE__ */ jsxRuntimeExports.jsxs(SectionList, { children: [
              /* @__PURE__ */ jsxRuntimeExports.jsxs(SectionListSection, { children: [
                /* @__PURE__ */ jsxRuntimeExports.jsxs(SectionListSectionHeader, { children: [
                  /* @__PURE__ */ jsxRuntimeExports.jsx(SectionListSectionTitle, { children: "General Settings" }),
                  /* @__PURE__ */ jsxRuntimeExports.jsx(SectionListSectionDescription, { children: "Configure the general settings for the auth plugin." })
                ] }),
                /* @__PURE__ */ jsxRuntimeExports.jsxs(SectionListSectionContent, { className: "auth:space-y-6", children: [
                  /* @__PURE__ */ jsxRuntimeExports.jsx(
                    FeatureComboboxFieldController,
                    {
                      label: "Auth Feature Path",
                      name: "authFeatureRef",
                      control,
                      canCreate: true,
                      description: "Specify the feature path where auth functionality will be generated"
                    }
                  ),
                  /* @__PURE__ */ jsxRuntimeExports.jsx(
                    SelectFieldController,
                    {
                      label: "Authentication Provider",
                      name: "implementationPluginKey",
                      control,
                      options: availableImplementations,
                      renderItemLabel: (item) => /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "auth:flex auth:flex-col auth:gap-2", children: [
                        /* @__PURE__ */ jsxRuntimeExports.jsx("div", { className: "auth:text-sm auth:font-medium", children: item.displayName }),
                        /* @__PURE__ */ jsxRuntimeExports.jsx("div", { className: "auth:text-sm auth:text-muted-foreground", children: item.description })
                      ] }),
                      getOptionLabel: (item) => item.displayName,
                      getOptionValue: (item) => item.key,
                      description: "The authentication provider to use for your project"
                    }
                  )
                ] })
              ] }),
              /* @__PURE__ */ jsxRuntimeExports.jsx(RoleEditorForm, { control })
            ] })
          ] }),
          /* @__PURE__ */ jsxRuntimeExports.jsx(FormActionBar, { form, allowSaveWithoutDirty: !pluginMetadata })
        ] })
      }
    )
  ] });
}

const {createPluginModule,webConfigSpec} = await importShared('@baseplate-dev/project-builder-lib');
const web = createPluginModule({
  name: "web",
  dependencies: {
    webConfig: webConfigSpec
  },
  initialize: ({ webConfig }, { pluginKey }) => {
    webConfig.components.set(pluginKey, AuthDefinitionEditor);
  }
});

export { web as default };
//# sourceMappingURL=__federation_expose_authCoreWeb-N-mh42Bs.js.map
