package kr.iotdoor.boot.web;

import jakarta.validation.Valid;
import kr.iotdoor.boot.model.user.AdminUserForm;
import kr.iotdoor.boot.service.UserManagementService;
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.RequestParam;

@Controller
public class AdminUserManagementController {

    private final UserManagementService userManagementService;

    public AdminUserManagementController(UserManagementService userManagementService) {
        this.userManagementService = userManagementService;
    }

    @GetMapping("/mfuc/user/list.do")
    public String userList(
        @RequestParam(name = "keyword", required = false) String keyword,
        @RequestParam(name = "userIdntfNo", required = false) String userIdntfNo,
        Model model
    ) {
        model.addAttribute("users", userManagementService.findUsers(keyword));
        model.addAttribute("keyword", keyword == null ? "" : keyword);
        model.addAttribute("form", userManagementService.getForm(userIdntfNo));
        applyPage(model);
        return "kr/iotdoor/boot/admin/user/list";
    }

    @PostMapping("/mfuc/user/save.do")
    public String saveUser(
        @Valid @ModelAttribute("form") AdminUserForm form,
        BindingResult bindingResult,
        @RequestParam(name = "keyword", required = false) String keyword,
        Model model
    ) {
        if (form.getUserIdntfNo() == null || form.getUserIdntfNo().isBlank()) {
            if (form.getPassword() == null || form.getPassword().isBlank()) {
                bindingResult.rejectValue("password", "required", "신규 사용자는 비밀번호가 필요합니다.");
            }
        }

        if (bindingResult.hasErrors()) {
            model.addAttribute("users", userManagementService.findUsers(keyword));
            model.addAttribute("keyword", keyword == null ? "" : keyword);
            applyPage(model);
            return "kr/iotdoor/boot/admin/user/list";
        }

        try {
            String savedId = userManagementService.save(form);
            String redirectKeyword = keyword == null || keyword.isBlank() ? "" : "&keyword=" + keyword.trim();
            return "redirect:/mfuc/user/list.do?userIdntfNo=" + savedId + "&saved=1" + redirectKeyword;
        } catch (IllegalArgumentException exception) {
            bindingResult.reject("saveError", exception.getMessage());
            model.addAttribute("users", userManagementService.findUsers(keyword));
            model.addAttribute("keyword", keyword == null ? "" : keyword);
            applyPage(model);
            return "kr/iotdoor/boot/admin/user/list";
        }
    }

    private void applyPage(Model model) {
        model.addAttribute("adminMenu", "user");
        model.addAttribute("adminSubMenu", "new");
        model.addAttribute("pageTitle", "사용자 관리");
        model.addAttribute("pageDescription", "관리자와 일반 사용자 계정을 등록하고 기본 정보를 관리합니다.");
    }
}
