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

import dev.fyloz.trial.colorrecipesexplorer.exception.model.EntityLinkedException;
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.Company;
import dev.fyloz.trial.colorrecipesexplorer.service.model.CompanyService;
import org.springframework.beans.factory.annotation.Autowired;
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_COMPANY;
import static dev.fyloz.trial.colorrecipesexplorer.web.WebsitePaths.REMOVER_COMPANY_SPECIFIC;

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

    private CompanyService companyService;

    @Autowired
    public CompanyRemoverController(CompanyService companyService) {
        this.companyService = companyService;
    }

    @GetMapping(REMOVER_COMPANY)
    public ModelAndView getPage(ModelAndView model) {
        return new ModelResponseBuilder(model)
                .withView(REMOVER_COMPANY)
                .addResponseData(ResponseDataType.COMPANIES, companyService.getAll())
                .build();
    }

    @PostMapping(REMOVER_COMPANY_SPECIFIC)
    public ModelAndView removeCompany(@PathVariable Long id) {
        ModelResponseBuilder modelResponseBuilder = new ModelResponseBuilder("");

        try {
            Company company = companyService.getById(id);
            companyService.delete(company);
            modelResponseBuilder.addResponseCode(ResponseCode.SUCCESS_DELETING_COMPANY, company.getName());
        } catch (EntityLinkedException ex) {
            modelResponseBuilder.addResponseCode(ResponseCode.COMPANY_LINKED, companyService.getById(id).getName());
        } catch (EntityNotFoundException ex) {
            modelResponseBuilder.addResponseCode(ResponseCode.COMPANY_NOT_FOUND, id);
        }

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