package com.example.demo.controller;

import com.example.demo.model.SystemSettings;
import com.example.demo.service.SystemSettingsService;
import jakarta.validation.Valid;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;

@Controller
@RequestMapping("/settings")
public class SettingsController {

    private final SystemSettingsService settingsService;

    public SettingsController(SystemSettingsService settingsService) {
        this.settingsService = settingsService;
    }

    @GetMapping
    public String showForm(Model model) {
        SystemSettings settings = settingsService.getOrCreate();
        model.addAttribute("pageTitle", "系统设置");
        model.addAttribute("settings", settings);
        return "settings/form";
    }

    @PostMapping
    public String save(@Valid @ModelAttribute("settings") SystemSettings form,
                       BindingResult bindingResult,
                       Model model) {
        if (bindingResult.hasErrors()) {
            model.addAttribute("pageTitle", "系统设置");
            return "settings/form";
        }
        settingsService.update(form);
        model.addAttribute("success", "保存成功");
        return "redirect:/settings";
    }
}


