import { validatePluginOptions } from "./options.js";
import { getRoutes as getFileUploadStatusRoutes } from "./routes/file-upload.js";
import { makeLoadFormPreHandler } from "./routes/index.js";
import { getRoutes as getQuestionRoutes } from "./routes/questions.js";
import { getRoutes as getRepeaterItemDeleteRoutes } from "./routes/repeaters/item-delete.js";
import { getRoutes as getRepeaterSummaryRoutes } from "./routes/repeaters/summary.js";
import { registerVision } from "./vision.js";
import { postcodeLookupPlugin } from "../postcode-lookup/index.js";
import { CacheService } from "../../services/index.js";
export const plugin = {
  name: '@defra/forms-engine-plugin',
  dependencies: ['@hapi/crumb', '@hapi/yar', 'hapi-pino'],
  multiple: true,
  async register(server, options) {
    options = validatePluginOptions(options);
    const {
      model,
      cache,
      saveAndExit,
      nunjucks: nunjucksOptions,
      viewContext,
      preparePageEventRequestOptions,
      onRequest,
      ordnanceSurveyApiKey
    } = options;
    const cacheService = typeof cache === 'string' ? new CacheService({
      server,
      cacheName: cache
    }) : cache;
    await registerVision(server, options);

    // Register the postcode lookup plugin only if we have an OS api key
    if (ordnanceSurveyApiKey) {
      await server.register({
        plugin: postcodeLookupPlugin,
        options: {
          ordnanceSurveyApiKey
        }
      });
    }
    server.expose('baseLayoutPath', nunjucksOptions.baseLayoutPath);
    server.expose('viewContext', viewContext);
    server.expose('cacheService', cacheService);
    server.expose('saveAndExit', saveAndExit);
    server.app.model = model;

    // In-memory cache of FormModel items, exposed
    // (for testing purposes) through `server.app.models`
    const itemCache = new Map();
    server.app.models = itemCache;
    const loadFormPreHandler = makeLoadFormPreHandler(server, options);
    const getRouteOptions = {
      pre: [{
        method: loadFormPreHandler
      }]
    };
    const postRouteOptions = {
      payload: {
        parse: true
      },
      pre: [{
        method: loadFormPreHandler
      }]
    };
    const routes = [...getQuestionRoutes(getRouteOptions, postRouteOptions, preparePageEventRequestOptions, onRequest), ...getRepeaterSummaryRoutes(getRouteOptions, postRouteOptions, onRequest), ...getRepeaterItemDeleteRoutes(getRouteOptions, postRouteOptions, onRequest), ...getFileUploadStatusRoutes()];
    server.route(routes); // TODO
  }
};
//# sourceMappingURL=plugin.js.map