/*
 * This file is part of the Meeds project (https://meeds.io/).
 * Copyright (C) 2020 - 2022 Meeds Association contact@meeds.io
 * This program is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Lesser 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
 * Lesser General Public License for more details.
 * You should have received a copy of the GNU Lesser General Public License
 * along with this program; if not, write to the Free Software Foundation,
 * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
 */
package io.meeds.tenant.provisioning.elasticsearch;

import java.util.Map;

import javax.annotation.PostConstruct;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.elasticsearch.core.ElasticsearchRestTemplate;
import org.springframework.data.elasticsearch.core.IndexOperations;

import io.meeds.tenant.provisioning.model.EmailTemplate;

/**
 * @deprecated This class is added to migrate Email Templates to use new Mapping
 *             to be compliant to Enum constants (using Keyword mapping instead
 *             of Short). It has to be removed just after migration done.
 */
@Deprecated(forRemoval = true)
@Configuration
public class EmailTemplateFixElasticsearchConfig {

  @Autowired
  private ElasticsearchRestTemplate elasticsearchTemplate;

  @PostConstruct
  public void init() {
    IndexOperations indexOperations = elasticsearchTemplate.indexOps(EmailTemplate.class);
    boolean indexExists = indexOperations.exists();
    if (indexExists) {
      @SuppressWarnings("unchecked")
      Map<String, Map<String, String>> propertiesMapping = (Map<String, Map<String, String>>) indexOperations.getMapping()
                                                                                                             .get("properties");
      Map<String, String> automaticStatusMapping = propertiesMapping.get("automaticStatus");
      if (automaticStatusMapping == null && indexOperations.delete()) {
        indexOperations.createWithMapping();
      }
    }
  }

}
