package com.example.todo;

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
public class TodoController {
    private final TodoService service;
    public TodoController(TodoService service) { this.service=service; }
    @GetMapping("/") String home() { return "redirect:/todos"; }
    @GetMapping("/todos") String list(Model model) {
        model.addAttribute("todos",service.list()); return "list";
    }
    @GetMapping("/todos/new") String newTodo(Model model) {
        model.addAttribute("todoForm",new TodoForm()); model.addAttribute("action","/todos");
        return "form";
    }
    @PostMapping("/todos") String create(@Valid @ModelAttribute("todoForm") TodoForm form,
                                        BindingResult errors, Model model) {
        if(errors.hasErrors()) { model.addAttribute("action","/todos"); return "form"; }
        service.create(form.getTitle(),form.isCompleted()); return "redirect:/todos";
    }
    @GetMapping("/todos/{id}/edit") String edit(@PathVariable String id,Model model) {
        Todo todo=service.get(id); TodoForm form=new TodoForm();
        form.setTitle(todo.getTitle()); form.setCompleted(todo.isCompleted());
        model.addAttribute("todoForm",form); model.addAttribute("action","/todos/"+id);
        return "form";
    }
    @PostMapping("/todos/{id}") String update(@PathVariable String id,
        @Valid @ModelAttribute("todoForm") TodoForm form,BindingResult errors,Model model) {
        if(errors.hasErrors()) { model.addAttribute("action","/todos/"+id); return "form"; }
        service.update(id,form.getTitle(),form.isCompleted()); return "redirect:/todos";
    }
    @PostMapping("/todos/{id}/delete") String delete(@PathVariable String id) {
        service.delete(id); return "redirect:/todos";
    }
}
