package com.cloudhandson.vpdbackoffice.web;

import com.cloudhandson.vpdbackoffice.service.BackofficeSchemaService;
import com.cloudhandson.vpdbackoffice.service.SettingService;
import org.springframework.dao.DataAccessException;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

@Controller
public class SettingController {

  private final SettingService settingService;
  private final BackofficeSchemaService backofficeSchemaService;

  public SettingController(SettingService settingService, BackofficeSchemaService backofficeSchemaService) {
    this.settingService = settingService;
    this.backofficeSchemaService = backofficeSchemaService;
  }

  @GetMapping("/settings")
  public String settings(Model model) {
    try {
      model.addAttribute("ordsBaseUrl", settingService.ordsBaseUrl());
    } catch (DataAccessException exception) {
      RuntimeErrorMessage error = RuntimeErrorMessages.dataAccess(exception);
      model.addAttribute("ordsBaseUrl", "");
      model.addAttribute("runtimeErrorTitle", error.title());
      model.addAttribute("runtimeErrorMessage", error.message());
    }
    return "settings";
  }

  @GetMapping("/settings/database")
  public String databaseSettings(Model model) {
    try {
      model.addAttribute("schemaPreflight", backofficeSchemaService.preflight());
    } catch (DataAccessException exception) {
      RuntimeErrorMessage error = RuntimeErrorMessages.dataAccess(exception);
      model.addAttribute("schemaPreflightErrorTitle", error.title());
      model.addAttribute("schemaPreflightErrorMessage", error.message());
    }
    return "settings-database";
  }

  @PostMapping("/settings/ords")
  public String updateOrds(
      @RequestParam String ordsBaseUrl,
      RedirectAttributes redirectAttributes
  ) {
    settingService.updateOrdsBaseUrl(ordsBaseUrl);
    redirectAttributes.addFlashAttribute("message", "ORDS 설정을 저장했습니다.");
    return "redirect:/settings";
  }

  @PostMapping("/settings/database/initialize")
  public String initializeSchema(
      @RequestParam String confirmation,
      RedirectAttributes redirectAttributes
  ) {
    if (!"DB 준비 실행".equals(confirmation)) {
      redirectAttributes.addFlashAttribute(
          "error", "DB 지원 DDL을 실행하려면 확인 문구 ‘DB 준비 실행’을 정확히 입력하세요.");
      return "redirect:/settings/database";
    }
    var results = backofficeSchemaService.initializeSchema();
    long failures = results.stream()
        .filter(result -> "FAILED".equalsIgnoreCase(result.status()))
        .count();
    redirectAttributes.addFlashAttribute("schemaResults", results);
    if (failures > 0) {
      redirectAttributes.addFlashAttribute("error", "백오피스 지원 DDL 실행 중 " + failures + "개 작업이 실패했습니다. 결과와 SQL을 확인하세요.");
    } else {
      redirectAttributes.addFlashAttribute("message", "백오피스 지원 테이블 DDL을 실행했습니다.");
    }
    return "redirect:/settings/database";
  }
}
