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.model.Mix;
import dev.fyloz.trial.colorrecipesexplorer.service.model.MixService;
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.servlet.ModelAndView;

import static dev.fyloz.trial.colorrecipesexplorer.web.WebsitePaths.*;

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

    private MixService mixService;

    public MixRemoverController(MixService mixService) {
        this.mixService = mixService;
    }

    @GetMapping(REMOVER_MIX_SPECIFIC)
    public ModelAndView removeMix(@PathVariable Long id) {
        ModelResponseBuilder modelResponseBuilder = new ModelResponseBuilder();

        try {
            Mix mix = mixService.getById(id);
            mixService.delete(mix);
            return modelResponseBuilder
                    .withRedirect(EDITOR_RECIPE_SPECIFIC, mix.getRecipe().getId())
                    .build();
        } catch (EntityNotFoundException ex) {
            modelResponseBuilder.addResponseCode(ResponseCode.MIX_NOT_FOUND, id);
        }

        return modelResponseBuilder
                .withRedirect(EDITOR_MIX_SPECIFIC, id)
                .build();
    }
}
