package com.kamco.cd.kamcoback.common.utils.zip;

import com.fasterxml.jackson.core.JsonFactory;
import com.fasterxml.jackson.core.JsonParser;
import com.fasterxml.jackson.core.JsonToken;
import com.fasterxml.jackson.databind.ObjectMapper;
import java.io.IOException;
import java.io.InputStream;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

@Slf4j
@Component
public class JsonStreamingFileProcessor implements ZipEntryProcessor {

  private final JsonFactory jsonFactory;

  public JsonStreamingFileProcessor(ObjectMapper objectMapper) {
    // ZipInputStream 보호용 설정
    objectMapper.configure(JsonParser.Feature.AUTO_CLOSE_SOURCE, false);
    this.jsonFactory = objectMapper.getFactory();
  }

  @Override
  public boolean supports(String fileName) {
    return fileName.toLowerCase().endsWith(".json");
  }

  @Override
  public void process(String fileName, InputStream is) throws IOException {

    log.info("JSON process start: {}", fileName);

    JsonParser parser = jsonFactory.createParser(is);

    // JSON 구조에 상관없이 token 단위로 순회
    while (parser.nextToken() != null) {
      handleToken(parser);
    }

    log.info("JSON process end: {}", fileName);
  }

  private void handleToken(JsonParser parser) throws IOException {
    JsonToken token = parser.currentToken();

    if (token == JsonToken.FIELD_NAME) {
      String fieldName = parser.getCurrentName();
      // TODO: json 파일 읽어야 할 내용 정의되면 항목 확정하기
      switch (fieldName) {
        case "type" -> {
          parser.nextToken();
          String type = parser.getValueAsString();
          log.info("type: {}", type);
        }
        case "name" -> {
          parser.nextToken();
          String name = parser.getValueAsString();
          log.info("Name: {}", name);
        }
        case "features" -> {
          parser.nextToken();
          String features = parser.readValueAsTree().toString();
          log.info("features: {}", features);
        }
        default -> {
          parser.nextToken();
          parser.skipChildren();
        }
      }
    }
  }
}
