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 { g as getAuthPluginDefinition } from './get-auth-plugin-definition-BL50g0cJ.js';
import { L as LOCAL_AUTH_MODELS } from './model-names-DrcaRxt1.js';
import { c as createLocalAuthPluginDefinitionSchema } from './plugin-definition-Ckl5hjD1.js';

function createLocalAuthPartialDefinition(authFeatureName) {
  return {
    models: [
      {
        name: LOCAL_AUTH_MODELS.user,
        featureRef: authFeatureName,
        model: {
          fields: [
            {
              name: "id",
              type: "uuid",
              options: { genUuid: true }
            },
            {
              name: "name",
              type: "string",
              isOptional: true
            },
            {
              name: "email",
              type: "string"
            },
            {
              name: "emailVerified",
              type: "boolean",
              options: { default: "false" }
            },
            {
              name: "updatedAt",
              type: "dateTime",
              options: { defaultToNow: true, updatedAt: true }
            },
            {
              name: "createdAt",
              type: "dateTime",
              options: { defaultToNow: true }
            }
          ],
          primaryKeyFieldRefs: ["id"],
          uniqueConstraints: [
            {
              fields: [{ fieldRef: "email" }]
            }
          ]
        },
        graphql: {
          objectType: {
            enabled: true,
            fields: [{ ref: "id" }, { ref: "email" }]
          }
        }
      },
      {
        name: LOCAL_AUTH_MODELS.userAccount,
        featureRef: authFeatureName,
        model: {
          fields: [
            {
              name: "id",
              type: "uuid",
              options: { genUuid: true }
            },
            {
              name: "userId",
              type: "uuid"
            },
            {
              name: "accountId",
              type: "string"
            },
            {
              name: "providerId",
              type: "string"
            },
            {
              name: "password",
              type: "string",
              isOptional: true
            },
            {
              name: "createdAt",
              type: "dateTime",
              options: { defaultToNow: true }
            },
            {
              name: "updatedAt",
              type: "dateTime",
              options: { defaultToNow: true, updatedAt: true }
            }
          ],
          primaryKeyFieldRefs: ["id"],
          uniqueConstraints: [
            {
              fields: [{ fieldRef: "accountId" }, { fieldRef: "providerId" }]
            }
          ],
          relations: [
            {
              name: "user",
              references: [{ localRef: "userId", foreignRef: "id" }],
              modelRef: LOCAL_AUTH_MODELS.user,
              foreignRelationName: "accounts",
              onDelete: "Cascade",
              onUpdate: "Restrict"
            }
          ]
        }
      },
      {
        name: LOCAL_AUTH_MODELS.userRole,
        featureRef: authFeatureName,
        model: {
          fields: [
            {
              name: "userId",
              type: "uuid"
            },
            {
              name: "role",
              type: "string"
            },
            {
              name: "updatedAt",
              type: "dateTime",
              options: { defaultToNow: true, updatedAt: true }
            },
            {
              name: "createdAt",
              type: "dateTime",
              options: { defaultToNow: true }
            }
          ],
          primaryKeyFieldRefs: ["userId", "role"],
          relations: [
            {
              name: "user",
              references: [{ localRef: "userId", foreignRef: "id" }],
              modelRef: LOCAL_AUTH_MODELS.user,
              foreignRelationName: "roles",
              onDelete: "Cascade",
              onUpdate: "Restrict"
            }
          ]
        }
      },
      {
        name: LOCAL_AUTH_MODELS.userSession,
        featureRef: authFeatureName,
        model: {
          fields: [
            {
              name: "id",
              type: "uuid",
              options: { genUuid: true }
            },
            {
              name: "userId",
              type: "uuid"
            },
            {
              name: "token",
              type: "string"
            },
            {
              name: "expiresAt",
              type: "dateTime"
            },
            {
              name: "renewedAt",
              type: "dateTime",
              options: { defaultToNow: true }
            },
            {
              name: "createdAt",
              type: "dateTime",
              options: { defaultToNow: true }
            },
            {
              name: "updatedAt",
              type: "dateTime",
              options: { defaultToNow: true, updatedAt: true }
            }
          ],
          primaryKeyFieldRefs: ["id"],
          uniqueConstraints: [
            {
              fields: [{ fieldRef: "token" }]
            }
          ],
          relations: [
            {
              name: "user",
              references: [{ localRef: "userId", foreignRef: "id" }],
              modelRef: LOCAL_AUTH_MODELS.user,
              foreignRelationName: "sessions",
              onDelete: "Cascade",
              onUpdate: "Restrict"
            }
          ]
        }
      },
      {
        name: LOCAL_AUTH_MODELS.authVerification,
        featureRef: authFeatureName,
        model: {
          fields: [
            {
              name: "id",
              type: "uuid",
              options: { genUuid: true }
            },
            {
              name: "type",
              type: "string"
            },
            {
              name: "identifier",
              type: "string"
            },
            {
              name: "value",
              type: "string"
            },
            {
              name: "userId",
              type: "uuid",
              isOptional: true
            },
            {
              name: "metadata",
              type: "json",
              isOptional: true
            },
            {
              name: "expiresAt",
              type: "dateTime"
            },
            {
              name: "createdAt",
              type: "dateTime",
              options: { defaultToNow: true }
            }
          ],
          primaryKeyFieldRefs: ["id"],
          uniqueConstraints: [
            {
              fields: [{ fieldRef: "type" }, { fieldRef: "identifier" }]
            }
          ],
          relations: [
            {
              name: "user",
              references: [{ localRef: "userId", foreignRef: "id" }],
              modelRef: LOCAL_AUTH_MODELS.user,
              foreignRelationName: "authVerifications",
              onDelete: "Cascade",
              onUpdate: "Restrict"
            }
          ]
        }
      }
    ]
  };
}

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

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

const {FormActionBar,MultiComboboxFieldController,SectionList,SectionListSection,SectionListSectionContent,SectionListSectionDescription,SectionListSectionHeader,SectionListSectionTitle} = await importShared('@baseplate-dev/ui-components');
const {useMemo} = await importShared('react');
function LocalAuthDefinitionEditor({
  definition: pluginMetadata,
  metadata,
  onSave
}) {
  const { definition, definitionContainer, saveDefinitionWithFeedback } = useProjectDefinition();
  const authPluginDefinitionSchema = useDefinitionSchema(
    createLocalAuthPluginDefinitionSchema
  );
  const authDefinition = getAuthPluginDefinition(definition);
  const roles = authDefinition.roles.filter((role) => !role.builtIn).map((role) => ({
    label: role.name,
    value: role.id
  }));
  const defaultValues = useMemo(() => {
    if (pluginMetadata?.config) {
      return pluginMetadata.config;
    }
    return {
      initialUserRoles: [],
      userAdminRoles: []
    };
  }, [pluginMetadata?.config]);
  const form = useResettableForm({
    resolver: a(authPluginDefinitionSchema),
    defaultValues
  });
  const { control, reset, handleSubmit } = form;
  const authFeature = definition.features.find(
    (f) => f.id === authDefinition.authFeatureRef
  );
  if (!authFeature) {
    throw new Error(
      `Auth feature not found for ref: ${authDefinition.authFeatureRef}`
    );
  }
  const partialDef = useMemo(
    () => createLocalAuthPartialDefinition(authFeature.name),
    [authFeature.name]
  );
  const diff = useMemo(
    () => diffDefinition(
      definitionContainer.schema,
      definitionContainer.definition,
      partialDef
    ),
    [definitionContainer, partialDef]
  );
  const onSubmit = handleSubmit(
    (data) => saveDefinitionWithFeedback(
      (draftConfig) => {
        const updatedData = {
          ...data
        };
        applyMergedDefinition(definitionContainer, partialDef)(draftConfig);
        PluginUtils.setPluginConfig(
          draftConfig,
          metadata,
          updatedData,
          definitionContainer
        );
      },
      {
        successMessage: "Successfully saved auth plugin!",
        onSuccess: () => {
          onSave();
        }
      }
    )
  );
  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.jsx("div", { className: "auth:pb-16", children: /* @__PURE__ */ jsxRuntimeExports.jsxs(SectionList, { children: [
            /* @__PURE__ */ jsxRuntimeExports.jsxs(SectionListSection, { children: [
              /* @__PURE__ */ jsxRuntimeExports.jsxs(SectionListSectionHeader, { children: [
                /* @__PURE__ */ jsxRuntimeExports.jsx(SectionListSectionTitle, { children: "Local Auth User Models" }),
                /* @__PURE__ */ jsxRuntimeExports.jsx(SectionListSectionDescription, { children: "The plugin will automatically configure the models it needs." })
              ] }),
              /* @__PURE__ */ jsxRuntimeExports.jsx(SectionListSectionContent, { className: "auth:space-y-6", children: /* @__PURE__ */ jsxRuntimeExports.jsx(
                DefinitionDiffAlert,
                {
                  diff,
                  upToDateMessage: "All required models are already configured correctly. No changes needed."
                }
              ) })
            ] }),
            /* @__PURE__ */ jsxRuntimeExports.jsxs(SectionListSection, { children: [
              /* @__PURE__ */ jsxRuntimeExports.jsxs(SectionListSectionHeader, { children: [
                /* @__PURE__ */ jsxRuntimeExports.jsx(SectionListSectionTitle, { children: "Initial User Setup" }),
                /* @__PURE__ */ jsxRuntimeExports.jsx(SectionListSectionDescription, { children: "In order to access the admin panel, an initial user must be created. To make it easier, the plugin will automatically add a seed script to create the initial user provided a .seed.env exists with the INTIIAL_USER_EMAIL and INTIIAL_USER_PASSWORD variables." })
              ] }),
              /* @__PURE__ */ jsxRuntimeExports.jsx(SectionListSectionContent, { className: "auth:space-y-6", children: /* @__PURE__ */ jsxRuntimeExports.jsx(
                MultiComboboxFieldController,
                {
                  label: "Initial User Roles",
                  name: "initialUserRoles",
                  control,
                  options: roles,
                  description: "The roles that will be assigned to the initial user."
                }
              ) })
            ] }),
            /* @__PURE__ */ jsxRuntimeExports.jsxs(SectionListSection, { children: [
              /* @__PURE__ */ jsxRuntimeExports.jsxs(SectionListSectionHeader, { children: [
                /* @__PURE__ */ jsxRuntimeExports.jsx(SectionListSectionTitle, { children: "User Management Permissions" }),
                /* @__PURE__ */ jsxRuntimeExports.jsx(SectionListSectionDescription, { children: "Configure which roles can manage users and assign roles to other users in the admin interface." })
              ] }),
              /* @__PURE__ */ jsxRuntimeExports.jsx(SectionListSectionContent, { className: "auth:space-y-6", children: /* @__PURE__ */ jsxRuntimeExports.jsx(
                MultiComboboxFieldController,
                {
                  label: "User Admin Roles",
                  name: "userAdminRoles",
                  control,
                  options: roles,
                  description: "Roles that can manage users and assign roles to other users."
                }
              ) })
            ] })
          ] }) }),
          /* @__PURE__ */ jsxRuntimeExports.jsx(
            FormActionBar,
            {
              form,
              allowSaveWithoutDirty: !pluginMetadata || diff.hasChanges
            }
          )
        ] })
      }
    )
  ] });
}

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, LocalAuthDefinitionEditor);
  }
});

export { web as default };
//# sourceMappingURL=__federation_expose_local-authCoreWeb-BY-mP3uS.js.map
