package com.cloudhandson.vpdbackoffice.service;

import com.cloudhandson.vpdbackoffice.domain.setting.BackofficeSetting;
import com.cloudhandson.vpdbackoffice.mapper.SettingMapper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.boot.ApplicationArguments;
import org.springframework.boot.ApplicationRunner;
import org.springframework.core.annotation.Order;
import org.springframework.dao.DataAccessException;
import org.springframework.stereotype.Component;

/** Removes the retired KB demo ORDS address without touching an operator-supplied ORDS endpoint. */
@Component
@Order(1)
public class HmmRuntimeSettingsInitializer implements ApplicationRunner {

  private static final Logger log = LoggerFactory.getLogger(HmmRuntimeSettingsInitializer.class);
  private static final String RETIRED_KB_ORDS_URL =
      "https://g329127dfd380ad-kbaipoc.adb.ap-osaka-1.oraclecloudapps.com/ords";

  private final SettingMapper settingMapper;

  public HmmRuntimeSettingsInitializer(SettingMapper settingMapper) {
    this.settingMapper = settingMapper;
  }

  @Override
  public void run(ApplicationArguments args) {
    try {
      BackofficeSetting setting = settingMapper.findByKey(SettingService.ORDS_BASE_URL);
      if (setting != null && RETIRED_KB_ORDS_URL.equals(normalize(setting.settingValue()))) {
        settingMapper.deleteByKey(SettingService.ORDS_BASE_URL);
        log.info("Removed retired KB demo ORDS setting; HMM MCP is the active integration");
      }
    } catch (DataAccessException exception) {
      // Do not prevent the backoffice from starting while its support schema is being prepared.
      log.warn("Skipped HMM runtime setting migration: {}", exception.getMostSpecificCause().getMessage());
    }
  }

  private String normalize(String value) {
    if (value == null) {
      return "";
    }
    String normalized = value.trim();
    while (normalized.endsWith("/")) {
      normalized = normalized.substring(0, normalized.length() - 1);
    }
    return normalized;
  }
}
