package com.eactive.testmaster.client.mapper;

import com.eactive.testmaster.client.dto.ApiLayoutDTO;
import com.eactive.testmaster.client.dto.ApiLayoutItemDTO;
import com.eactive.testmaster.client.entity.ApiLayout;
import com.eactive.testmaster.client.entity.ApiRequestInfo;
import com.eactive.testmaster.client.repository.ApiLayoutRepository;
import com.eactive.testmaster.client.repository.ApiRequestRepository;
import com.eactive.testmaster.common.mapper.CommonMapper;
import com.fasterxml.jackson.databind.ObjectMapper;
import java.util.List;
import org.mapstruct.Mapper;
import org.mapstruct.Mapping;
import org.mapstruct.ReportingPolicy;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

@Mapper(componentModel = "spring",
    uses = {CommonMapper.class, ApiLayoutItemMapper.class},
    unmappedTargetPolicy = ReportingPolicy.IGNORE)
@Component
public abstract class ApiLayoutMapper {

    ObjectMapper objectMapper = new ObjectMapper();

    @Autowired
    private ApiLayoutRepository apiLayoutRepository;

    @Autowired
    private ApiRequestRepository apiRequestRepository;


    @Mapping(target = "apiRequestInfo", source = "apiRequestId")
    public abstract ApiLayout map(ApiLayoutDTO dto);

    @Mapping(target = "apiRequestId", source = "apiRequestInfo")
    public abstract ApiLayoutDTO map(ApiLayout entity);


    public String treeToString(ApiLayoutItemDTO value) {
        if (value == null) {
            return null;
        }
        try {
            return objectMapper.writeValueAsString(value);
        } catch (Exception e) {
            throw new IllegalArgumentException("Failed to convert ApiLayoutItemDTO to JSON", e);
        }

    }

    public ApiLayoutItemDTO stringToTree(String value) {
        if (value == null) {
            return null;
        }
        try {
            return objectMapper.readValue(value, ApiLayoutItemDTO.class);
        } catch (Exception e) {
            throw new IllegalArgumentException("Failed to convert JSON to ApiLayoutItemDTO", e);
        }

    }

    public ApiRequestInfo mapApiRequestInfo(String id) {
        if (id == null) {
            return null;
        }
        return apiRequestRepository.findById(id).orElseThrow(() -> new IllegalArgumentException("No ApiRequest found for ID: " + id));
    }

    public String mapApiRequestId(ApiRequestInfo entity) {
        if (entity == null) {
            return null;
        }
        return entity.getId();
    }


    public ApiLayout map(String id) {
        if (id == null) {
            return null;
        }
        return apiLayoutRepository.findById(id).orElseThrow(() -> new IllegalArgumentException("No ApiLayout found for ID: " + id));
    }

//    public abstract List<ApiLayout> mapLayouts(List<ApiLayoutDTO> dtos);

    public abstract List<ApiLayoutDTO> mapLayoutDTOs(List<ApiLayout> entities);
}
