package com.jasamedika.medifirst2000.task.schedule;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.jasamedika.medifirst2000.service.MigrasiPasienService;
import com.jasamedika.medifirst2000.util.CommonUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.HttpEntity;
import org.springframework.http.ResponseEntity;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
import org.springframework.web.client.RestTemplate;

import java.net.URI;
import java.net.URISyntaxException;
import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import static com.jasamedika.medifirst2000.task.schedule.config.HeaderHandler.getHttpHeaders;
import static org.springframework.http.HttpMethod.GET;

/**
 * @author salmanoe
 * @version 1.0.0
 * @since 11/10/2023
 */
@Component
public class MigrasiPasienTask {
	private static final Logger LOGGER = LoggerFactory.getLogger(MigrasiPasienTask.class);

	@Autowired
	private RestTemplate restTemplate;

	@Autowired
	private ObjectMapper objectMapper;

	@Autowired
	private MigrasiPasienService migrasiPasienService;

	@Value("${app.etl.migrasi.pasien}")
	String baseUrl;

	@Scheduled(cron = "0 0 18 * * ?")
	public void newMigrate() {
		LOGGER.info("Task MigrasiPasienTask.newMigrate {}", LocalDateTime.now());

		migrasiPasienService.newMigrate();
	}

	@Scheduled(cron = "0 0 0 * * ?")
	public void setStatusTerkirim() throws URISyntaxException {
		LOGGER.info("Task MigrasiPasienTask.setStatusTerkirim {}", LocalDateTime.now());

		URI uri = new URI(baseUrl + "/no-rekam-medis");
		HttpEntity<Object> entity = new HttpEntity<>(null, getHttpHeaders());
		ResponseEntity<Object> exchange = restTemplate.exchange(uri, GET, entity, Object.class);
		if (CommonUtil.isNotNullOrEmpty(exchange.getBody())) {
			Map<String, Object> dto = objectMapper.convertValue(exchange.getBody(), HashMap.class);
			if (CommonUtil.isNotNullOrEmpty(dto) && CommonUtil.isNotNullOrEmpty(dto.get("response"))) {
				List<String> noRekamMedisList = objectMapper.convertValue(dto.get("response"), List.class);
				migrasiPasienService.setStatus(noRekamMedisList);
			}
		}
	}
}
