package com.eactive.eai.common.logger.mapper;

import com.eactive.eai.common.logger.HttpAdapterExtraHeaderVo;
import com.eactive.eai.common.logger.HttpAdapterExtraLogVo;
import com.eactive.eai.data.entity.onl.logger.HttpAdapterExtraLog;
import com.eactive.eai.data.mapper.BaseMapperConfig;
import com.eactive.eai.data.mapper.GenericMapper;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;
import lombok.extern.slf4j.Slf4j;
import org.mapstruct.*;

import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.util.Collections;
import java.util.List;

@Slf4j
@Mapper(config = BaseMapperConfig.class)
public abstract class HttpAdapterExtraLogMapper implements GenericMapper<HttpAdapterExtraLogVo, HttpAdapterExtraLog> {

    private final static ObjectMapper objectMapper = new ObjectMapper();
	private static final DateTimeFormatter	SDF_YYYYMMDD = DateTimeFormatter.ofPattern( "yyyyMMdd");

    @Override
    @Mapping(source = "id.guid", target = "guid")
    @Mapping(source = "id.serviceProcessNumber", target = "serviceProcessNumber")
    abstract public HttpAdapterExtraLogVo toVo(HttpAdapterExtraLog entity);

    @Override
    @InheritInverseConfiguration
    abstract public HttpAdapterExtraLog toEntity(HttpAdapterExtraLogVo vo);

    @AfterMapping
    public void voToEntity(@MappingTarget HttpAdapterExtraLog entity, HttpAdapterExtraLogVo vo) {

        // 1. Set weekday for partition table
//        DayOfWeek dayOfWeek = LocalDate.now().getDayOfWeek(); // 현재 요일
//        int dayOfWeekNumber = dayOfWeek.getValue() % 7 + 1; // 1 (일요일)부터 7 (토요일)까지
//        entity.getId().setWeekday(dayOfWeekNumber);
        
//        String prcs_date = SDF_YYYYMMDD.format(ZonedDateTime.now());
        String prcs_date = LocalDate.now().format(SDF_YYYYMMDD);
        entity.getId().setPrcsDate(prcs_date);

        // 2. Set Content
        try {
            String headerContent = objectMapper.writeValueAsString(vo.getHeaderList());
            entity.setHeaderContent(headerContent);
        } catch (JsonProcessingException e) {
            log.warn("Http Header Json Parse 실패", e);
            entity.setHeaderContent("[{ \"error\": \"parse error\"}]");
        }

    }

    /**
     * Entity → VO 변환 후 추가 처리
     */
    @AfterMapping
    protected void entityToVo(@MappingTarget HttpAdapterExtraLogVo vo, HttpAdapterExtraLog entity) {
        String headerContent = entity.getHeaderContent();
        if (headerContent == null || headerContent.isEmpty()) {
            vo.setHeaderList(Collections.emptyList());
            return;
        }

        try {
            List<HttpAdapterExtraHeaderVo> headerList = objectMapper.readValue(
                    headerContent,
                    new TypeReference<List<HttpAdapterExtraHeaderVo>>() {}
            );
            vo.setHeaderList(headerList);
        } catch (JsonProcessingException e) {
            log.warn("Http Header 역직렬화 실패", e);
            vo.setHeaderList(Collections.emptyList());
        }
    }
}
