package dev.fyloz.trial.colorrecipesexplorer.web.controller.thymeleaf.removers;

import dev.fyloz.trial.colorrecipesexplorer.exception.model.EntityNotFoundException;
import dev.fyloz.trial.colorrecipesexplorer.web.response.ModelResponseBuilder;
import dev.fyloz.trial.colorrecipesexplorer.web.response.ResponseCode;
import dev.fyloz.trial.colorrecipesexplorer.web.response.ResponseDataType;
import dev.fyloz.trial.colorrecipesexplorer.model.Recipe;
import dev.fyloz.trial.colorrecipesexplorer.service.model.RecipeService;
import org.springframework.context.annotation.Profile;
import org.springframework.stereotype.Controller;
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.servlet.ModelAndView;

import static dev.fyloz.trial.colorrecipesexplorer.web.WebsitePaths.REMOVER_RECIPE;
import static dev.fyloz.trial.colorrecipesexplorer.web.WebsitePaths.REMOVER_RECIPE_SPECIFIC;

@Controller
@Profile("thymeleaf")
public class RecipeRemoverController {

    private RecipeService recipeService;

    public RecipeRemoverController(RecipeService recipeService) {
        this.recipeService = recipeService;
    }

    @GetMapping(REMOVER_RECIPE)
    public ModelAndView getPage(ModelAndView model) {
        return new ModelResponseBuilder(model)
                .withView(REMOVER_RECIPE)
                .addResponseData(ResponseDataType.RECIPE_MAP, recipeService.getAllMappedByCompany())
                .build();
    }

    @PostMapping(REMOVER_RECIPE_SPECIFIC)
    public ModelAndView removeRecipe(@PathVariable Long id) {
        ModelResponseBuilder modelResponseBuilder = new ModelResponseBuilder();

        try {
            Recipe recipe = recipeService.getById(id);
            recipeService.delete(recipe);
            modelResponseBuilder.addResponseCode(ResponseCode.SUCCESS_DELETING_RECIPE, recipe.getName());
        } catch (EntityNotFoundException ex) {
            modelResponseBuilder.addResponseCode(ResponseCode.RECIPE_NOT_FOUND, id);
        }

        return getPage(modelResponseBuilder.build());
    }
}
