package com.weighttracker.controller;

import com.weighttracker.model.User;
import com.weighttracker.service.UserService;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

@Controller
@RequestMapping("/usuarios")
public class UserController {

    private final UserService service;

    public UserController(UserService service) {
        this.service = service;
    }

    @GetMapping
    public String list(Model m) {
        m.addAttribute("usuarios", service.findAll());
        return "usuarios";
    }

    @GetMapping("/nuevo")
    public String nuevo(Model m) {
        m.addAttribute("usuario", new User());
        return "usuario-form";
    }

    @PostMapping("/guardar")
    public String guardar(@ModelAttribute("usuario") User u) {
        service.save(u);
        return "redirect:/usuarios";
    }

    @GetMapping("/{id}/editar")
    public String editar(@PathVariable Long id, Model model) {
        User user = service.findById(id);
        model.addAttribute("usuario", user);
        return "usuario-form";
    }

    @PostMapping("/{id}/eliminar")
    public String eliminar(@PathVariable Long id) {
        service.deleteById(id);
        return "redirect:/usuarios";
    }

}
