package com.jasamedika.medifirst2000.controller;

import com.jasamedika.medifirst2000.constants.Constants;
import com.jasamedika.medifirst2000.constants.MessageResource;
import com.jasamedika.medifirst2000.controller.base.LocaleController;
import com.jasamedika.medifirst2000.dto.ProdukPaketDto;
import com.jasamedika.medifirst2000.exception.ServiceVOException;
import com.jasamedika.medifirst2000.service.ProdukPaketService;
import com.jasamedika.medifirst2000.vo.ProdukVO;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.orm.jpa.JpaSystemException;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.Map;

import static com.jasamedika.medifirst2000.core.web.WebConstants.HttpHeaderInfo.LABEL_SUCCESS;
import static com.jasamedika.medifirst2000.util.rest.RestUtil.getJsonHttptatus;
import static com.jasamedika.medifirst2000.util.rest.RestUtil.getJsonResponse;
import static org.springframework.http.HttpStatus.CREATED;
import static org.springframework.http.MediaType.APPLICATION_JSON_VALUE;
import static org.springframework.web.bind.annotation.RequestMethod.POST;

/**
 * @author salmanoe
 * @version 1.0.0
 * @since 14/11/2024
 */
@RestController
@RequestMapping("/produk")
public class ProdukController extends LocaleController<ProdukVO> {

	private static final Logger LOGGER = LoggerFactory.getLogger(ProdukController.class);

	@Autowired
	private ProdukPaketService produkPaketService;

	@RequestMapping(value = "/paket", method = POST, produces = APPLICATION_JSON_VALUE, consumes = APPLICATION_JSON_VALUE)
	public ResponseEntity<Object> simpanDiskonTagihan(HttpServletRequest request, @RequestBody ProdukPaketDto dto) {
		try {
			produkPaketService.save(dto);
			mapHeaderMessage.put(LABEL_SUCCESS, getMessage(MessageResource.LABEL_SUCCESS, request));
			return getJsonResponse(dto, CREATED, mapHeaderMessage);
		} catch (ServiceVOException e) {
			LOGGER.error("Got ServiceVOException {} when simpan produk paket", e.getMessage());
			Map<String, String> error = new HashMap<>();
			error.put("bad_request", e.getMessage());
			return getJsonResponse(null, HttpStatus.BAD_REQUEST, error);
		} catch (JpaSystemException jse) {
			LOGGER.error("Got JpaSystemException {} when simpan produk paket", jse.getMessage());
			addHeaderMessage(Constants.MessageInfo.ERROR_MESSAGE, jse.getMessage());
			return getJsonHttptatus(HttpStatus.CONFLICT, mapHeaderMessage);
		}
	}

}
