package com.platform2easy.genesis.web.controller;

import com.platform2easy.genesis.domain.model.Commoditiy;
import com.platform2easy.genesis.domain.service.CommodityService;
import lombok.AllArgsConstructor;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;

@Controller
@RequestMapping("commodity")
@AllArgsConstructor
public class CommodityController {

    private final CommodityService service;

    private String abrirFormulario(Commoditiy commoditiy, String titulo, Model model) {
        model.addAttribute("titulo", titulo);
        model.addAttribute("commodity", commoditiy);
        return "commodity/form";
    }

    @GetMapping()
    public String iniciar(Commoditiy commoditiy, Model model) {
        return abrirFormulario(commoditiy, "Cadastrar Commodity", model);
    }

    @GetMapping("edit/{id}")
    public String editar(@PathVariable Long id, Model model) {
        return abrirFormulario(service.buscarPorId(id), "Editar Commodity", model);
    }

    @PostMapping()
    public String salvar(Commoditiy commoditiy, Model model) {
        service.salvar(commoditiy);
        return "redirect:/commodity/all";
    }

    @GetMapping("remove/{id}")
    public String remover(@PathVariable Long id, Model model) {
        service.deletarPorId(id);
        return "redirect:/commodity/all";
    }

    @GetMapping("all")
    public String listar(Model model) {
        model.addAttribute("titulo", "Commodities");
        model.addAttribute("commodities", service.listarTodos());
        return "commodity/list";
    }
}
