package com.example.springip.lab3.mvc;

import com.example.springip.lab3.dto.EmployeeDto;
import com.example.springip.lab3.dto.PositionDto;
import com.example.springip.lab3.service.EmployeeService;
import com.example.springip.lab3.service.PositionService;
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.*;

@Controller
@RequestMapping("/position")
public class PositionMvcController {
    private final PositionService positionService;

    public PositionMvcController(PositionService positionService) {
        this.positionService = positionService;
    }

    @GetMapping
    public String getPositions(Model model) {
        model.addAttribute("positions",
                positionService.findAllPositions().stream()
                        .map(PositionDto::new)
                        .toList());
        return "position";
    }

    @GetMapping(value = {"/edit/", "/edit/{id}"})
    public String editPosition(@PathVariable(required = false) Long id,
                              Model model) {
        if (id == null || id <= 0) {
            model.addAttribute("positionDto", new PositionDto());
        } else {
            model.addAttribute("positionId", id);
            model.addAttribute("positionDto", new PositionDto(positionService.findPosition(id)));
        }
        return "position-edit";
    }

    @PostMapping(value = {"/", "/{id}"})
    public String savePosition(@PathVariable(required = false) Long id,
                              @ModelAttribute @Valid PositionDto positionDto,
                              BindingResult bindingResult,
                              Model model) {
        if (bindingResult.hasErrors()) {
            model.addAttribute("errors", bindingResult.getAllErrors());
            return "position-edit";
        }
        if (id == null || id <= 0) {
            positionService.addPosition(positionDto.getName());
        } else {
            positionService.updatePosition(id, positionDto.getName());
        }
        return "redirect:/position";
    }



    @PostMapping("/delete/{id}")
    public String deleteEmployee(@PathVariable Long id) {
        positionService.deletePosition(id);
        return "redirect:/position";
    }
}
