import path from 'path';
import {
  REDOCLY_TEAMS_RBAC,
  PUBLIC_RBAC_SCOPE_ITEM,
} from '@redocly/realm/dist/shared/constants.js';
import { fromCurrentDir } from '@redocly/realm/dist/server/utils/paths.js';

import type { ExternalPlugin } from '@redocly/realm/dist/server/plugins/types';

import {
  INITIATE_LOGIN_SLUG,
  LOGIN_CALLBACK_SLUG,
  LOGIN_PAGE_SLUG,
  SSO_PROVIDER_TYPE,
  TEMPLATE_ID,
} from './constants.js';
import { ssoConfigSchema } from './config.js';

export default function asyncAPIDocsPlugin(): ExternalPlugin {
  return {
    id: 'gravitee-sso',
    processContent: async (actions) => {
      actions.createTemplate(TEMPLATE_ID, path.resolve(__dirname, 'GraviteeLoginPage'));

      actions.addRoute({
        duplicateInAllLocales: true,
        excludeFromSidebar: true,
        slug: LOGIN_PAGE_SLUG,
        [REDOCLY_TEAMS_RBAC]: PUBLIC_RBAC_SCOPE_ITEM, // allow access to this page for all teams
        fsPath: LOGIN_PAGE_SLUG,
        templateId: TEMPLATE_ID,
        getStaticData: async () => ({
          props: { frontmatter: {}, seo: { title: 'Login page' } },
        }),
      });

      const initiateLoginRouteHandler = fromCurrentDir(
        import.meta.url,
        './handle-initiate-login.js',
      );
      const loginCallbackRouteHandler = fromCurrentDir(
        import.meta.url,
        './handle-login-callback.js',
      );

      actions.addCustomSsoProvider({
        loginUrl: INITIATE_LOGIN_SLUG,
        type: SSO_PROVIDER_TYPE,
        apiRoutes: [
          {
            route: {
              slug: INITIATE_LOGIN_SLUG,
              [REDOCLY_TEAMS_RBAC]: PUBLIC_RBAC_SCOPE_ITEM,
            },
            handlerImportPath: initiateLoginRouteHandler,
          },
          {
            route: {
              slug: LOGIN_CALLBACK_SLUG,
              [REDOCLY_TEAMS_RBAC]: PUBLIC_RBAC_SCOPE_ITEM,
            },
            handlerImportPath: loginCallbackRouteHandler,
          },
        ],
      });
    },
    ssoConfigSchema: ssoConfigSchema as any,
  };
}
