package com.cloudhandson.vpdbackoffice.web;

import com.cloudhandson.vpdbackoffice.domain.securityscript.SecuritySqlScriptSummary;
import com.cloudhandson.vpdbackoffice.service.AppException;
import com.cloudhandson.vpdbackoffice.service.SecuritySqlScriptExplanationService;
import com.cloudhandson.vpdbackoffice.service.SecuritySqlScriptService;
import java.util.List;
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;

/** Read-only page for the curated ASO, ORDS, and Select AI deployment scripts. */
@Controller
public class SecuritySqlScriptController {

  private final SecuritySqlScriptService securitySqlScriptService;
  private final SecuritySqlScriptExplanationService explanationService;

  public SecuritySqlScriptController(
      SecuritySqlScriptService securitySqlScriptService,
      SecuritySqlScriptExplanationService explanationService
  ) {
    this.securitySqlScriptService = securitySqlScriptService;
    this.explanationService = explanationService;
  }

  @GetMapping("/security-sql-scripts")
  public String scripts(@RequestParam(required = false) String script, Model model) {
    List<SecuritySqlScriptSummary> scripts = securitySqlScriptService.list();
    model.addAttribute("scripts", scripts);
    if (scripts.isEmpty()) {
      model.addAttribute("errorMessage", "표시할 보안 SQL 스크립트가 없습니다.");
      return "security-sql-scripts";
    }

    String selectedId = script == null || script.isBlank() ? scripts.getFirst().scriptId() : script;
    try {
      model.addAttribute("selectedScript", securitySqlScriptService.find(selectedId));
    } catch (AppException exception) {
      model.addAttribute("errorMessage", exception.getMessage());
      model.addAttribute("selectedScript", securitySqlScriptService.find(scripts.getFirst().scriptId()));
    }
    return "security-sql-scripts";
  }

  @PostMapping("/security-sql-scripts/explanation")
  public String explain(@RequestParam String script, Model model) {
    try {
      model.addAttribute("explanation", explanationService.explain(script));
    } catch (AppException exception) {
      model.addAttribute("errorMessage", exception.getMessage());
    }
    return "fragments/security-sql-script-explanation :: explanation";
  }
}
