package com.platform2easy.genesis.web.controller.cerc;

import com.platform2easy.genesis.domain.model.cerc.SolicitacaoRegistroCpr;
import com.platform2easy.genesis.domain.model.cerc.StatusSolicitacaoRegistroCpr;
import com.platform2easy.genesis.domain.service.cerc.ContratoValorCprService;
import com.platform2easy.genesis.domain.service.cerc.EmissaoCprService;
import com.platform2easy.genesis.domain.service.cerc.SolicitacaoRegistroCprService;
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.ModelAttribute;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;

@Controller
@RequestMapping("cpr/register")
@AllArgsConstructor
public class SolicitacaoRegistroCprController {

    private static final String FORM = "cpr/register/form";
    private static final String LIST = "cpr/register/list";
    private static final String REDIRECT_ALL = "redirect:/cpr/register/all";
    private static final String TITLE_PAGE = "titlePage";


    private final SolicitacaoRegistroCprService service;
    private final ContratoValorCprService contratoValorCprService;
    private final EmissaoCprService emissaoCprService;

    private String openForm(SolicitacaoRegistroCpr cprRegister, String title, Model model) {
        model.addAttribute(TITLE_PAGE, title);
        model.addAttribute("cprRegister", cprRegister);
        model.addAttribute("contracts", contratoValorCprService.listAll());
        model.addAttribute("emissions", emissaoCprService.listAll());
        return FORM;
    }

    @GetMapping()
    public String init(SolicitacaoRegistroCpr cprRegister, Model model) {
        return openForm(cprRegister, "Registrar CPR", model);
    }

    @GetMapping("edit/{id}")
    public String edit(@PathVariable Long id, Model model) {
        return openForm(service.getById(id), "Registro de CPR", model);
    }

    @GetMapping("send/{id}")
    public String send(@PathVariable Long id, Model model) {
        var registro = service.getById(id);
        registro.setStatus(StatusSolicitacaoRegistroCpr.ACEITO);
        service.save(registro);
        return REDIRECT_ALL;
    }

    @PostMapping()
    public String save(@ModelAttribute SolicitacaoRegistroCpr cprRegister) {
        service.save(cprRegister);
        return REDIRECT_ALL;
    }

    @GetMapping("remove/{id}")
    public String remove(@PathVariable Long id, Model model) {
        service.delete(id);
        return REDIRECT_ALL;
    }

    @GetMapping("all")
    public String listAll(Model model) {
        model.addAttribute(TITLE_PAGE, "Registros de CPR's");
        model.addAttribute("cprRegisters", service.listAll());
        return LIST;
    }


}
