/*
 * Copyright (C) 2019 StApps
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Affero General Public License as
 * published by the Free Software Foundation, either version 3 of the
 * License, or (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU Affero General Public License for more details.
 *
 * You should have received a copy of the GNU Affero General Public License
 * along with this program.  If not, see <https://www.gnu.org/licenses/>.
 */
import {Client} from '@elastic/elasticsearch';
import {SCThingType} from '@openstapps/core';
import type {AggregationSchema} from '@openstapps/core/lib/mappings/aggregations.json.js';
import type {ElasticsearchTemplateCollection} from '@openstapps/core/lib/mappings/mappings.json.js';
import {readFileSync} from 'fs';
import path from 'path';

const mappingsPath = path.resolve('node_modules', '@openstapps', 'core', 'lib', 'mappings');

export const mappings = JSON.parse(
  readFileSync(path.resolve(mappingsPath, 'mappings.json'), 'utf8'),
) as ElasticsearchTemplateCollection;
export const aggregations = JSON.parse(
  readFileSync(path.resolve(mappingsPath, 'aggregations.json'), 'utf8'),
) as AggregationSchema;

/**
 * Prepares all indices
 *
 * This includes applying the mapping, settings
 * @param client An elasticsearch client to use
 * @param type the SCThingType of which the template should be set
 */
export async function putTemplate(client: Client, type: SCThingType) {
  const sanitizedType = `template_${type.replaceAll(/\s/g, '_')}`;

  return client.indices.putTemplate({
    body: mappings[sanitizedType],
    name: sanitizedType,
  });
}
