package incheon.sgp.aat.service.impl;

import incheon.sgp.aat.mapper.SgpAatMapper;
import incheon.sgp.aat.service.SgpAatService;
import incheon.sgp.aat.vo.SgpAatVO;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.regex.Pattern;

/**
 * @author : HyeonBin, Kang
 * @version 1.4
 * @Class Name : SgpAatServiceImpl.java
 * @Description : 건축상 수상작 조회 Service 구현체 
 * @Modification Information
 * 개정일자              개정자                  개정내용
 * ------------------ ----------- --------------------------
 * 2025. 10. 14       HyeonBin, Kang         최초생성
 * <p>
 * Copyright 2025. 올포랜드 INC. All rights reserved.
 * @since : 2025.10.14
 */
@Slf4j
@Service
@RequiredArgsConstructor
public class SgpAatServiceImpl implements SgpAatService {

  // 한글 이름 패턴 (2~4자)
  private static final Pattern KOREAN_NAME_PATTERN = Pattern.compile("^[가-힣]{2,4}$");
  // 회사 키워드
  private static final String[] COMPANY_KEYWORDS =
      {"건축", "건설", "사무소", "엔지니어링", "㈜", "(주)", "종합", "설계", "주식회사"};
  private final SgpAatMapper sgpAatMapper;

  @Override
  public List<SgpAatVO> selectAwardList(Integer yr, String wnawd_se_se_cd, String keyword,
      String sgg_cd, String emd_cd) {

    List<SgpAatVO> result =
        sgpAatMapper.selectAwardList(yr, wnawd_se_se_cd, keyword, sgg_cd, emd_cd);

    result.forEach(vo -> {
      // 개인정보 마스킹 처리
      maskSensitiveInfo(vo);
      // 이미지 경로 설정
      attachImageUrls(vo);
    });

    log.info("수상작 목록 조회 완료: {}건", result.size());
    return result;
  }

  @Override
  public List<Integer> selectYearList() {
    return sgpAatMapper.selectYearList();
  }

  @Override
  public List<SgpAatVO> selectAwardCodeList() {
    return sgpAatMapper.selectAwardCodeList();
  }

  @Override
  public List<SgpAatVO> selectSggList() {
    return sgpAatMapper.selectSggList();
  }

  @Override
  public List<SgpAatVO> selectEmdListBySgg(String sgg_cd) {
    return sgpAatMapper.selectEmdListBySgg(sgg_cd);
  }

  @Override
  public List<SgpAatVO> selectAllEmdList() {
    return sgpAatMapper.selectAllEmdList();
  }

  /**
   * 수상작 연도/PK 기반으로 이미지 URL 자동 구성
   */
  private void attachImageUrls(SgpAatVO vo) {
    if (vo == null || vo.getImageUrl() == null || vo.getImageUrl().isBlank()) {
      vo.setImageUrls(new ArrayList<>());
      return;
    }

    List<String> imageUrls = new ArrayList<>();

    String basePath = vo.getImageUrl().trim();
    String fileName = vo.getImageNm();

    // 최종 이미지 URL (ex: http://…/2001/58.files/image001.jpg)
    String imageUrl = basePath + (basePath.endsWith("/") ? "" : "/") + fileName;

    try {
      // 파일명에서 imageXXX.jpg의 숫자 추출
      Pattern pattern = Pattern.compile("image(\\d+)\\.jpg$");
      java.util.regex.Matcher matcher = pattern.matcher(imageUrl);

      if (matcher.find()) {
        int imageCount = Integer.parseInt(matcher.group(1));

        // 기본 경로 (image001.jpg 이전 부분)
        String finalBasePath = imageUrl.substring(0, matcher.start());

        // 1부터 imageCount까지 URL 생성
        for (int i = 1; i <= imageCount; i++) {
          String url = String.format("%simage%03d.jpg", finalBasePath, i);
          imageUrls.add(url);
        }
      } else {
        // 패턴이 매칭되지 않으면 원본 하나만
        imageUrls.add(imageUrl);
      }
    } catch (NumberFormatException e) {
      log.warn("이미지 URL 파싱 실패: {}, 원본 URL 사용", imageUrl, e);
      imageUrls.add(imageUrl);
    }

    vo.setImageUrls(imageUrls);
  }

  /**
   * VO 객체의 개인정보 마스킹 처리
   */
  private void maskSensitiveInfo(SgpAatVO vo) {
    vo.setDsgnr(maskName(vo.getDsgnr()));
    vo.setBldr(maskName(vo.getBldr()));
  }

  /**
   * 이름 마스킹 처리 (회사명은 유지, 개인 이름만 마스킹)
   * 쉼표로 구분된 여러 항목을 처리하고, 각 항목에서 회사명과 이름을 분리
   */
  private String maskName(String input) {
    if (input == null || input.isBlank()) {
      return input;
    }

    // 1. 쉼표로 구분된 항목들을 먼저 분리
    String[] items = input.split(",");
    StringBuilder result = new StringBuilder();

    for (int i = 0; i < items.length; i++) {
      String item = items[i].trim();

      // 2. 각 항목을 공백으로 분리하여 처리
      String maskedItem = maskItem(item);
      result.append(maskedItem);

      if (i < items.length - 1) {
        result.append(", ");
      }
    }

    return result.toString();
  }

  /**
   * 단일 항목(회사명+이름 조합)의 마스킹 처리
   */
  private String maskItem(String item) {
    if (item == null || item.isBlank()) {
      return item;
    }

    String[] words = item.split("\\s+");
    StringBuilder result = new StringBuilder();

    for (int i = 0; i < words.length; i++) {
      String word = words[i];

      // 회사 키워드가 포함되지 않고 한글 이름 패턴인 경우에만 마스킹
      if (!isCompanyName(word) && KOREAN_NAME_PATTERN.matcher(word).matches()) {
        word = maskSingleName(word);
      }

      result.append(word);
      if (i < words.length - 1) {
        result.append(" ");
      }
    }

    return result.toString();
  }

  /**
   * 회사명 여부 확인
   */
  private boolean isCompanyName(String word) {
    for (String keyword : COMPANY_KEYWORDS) {
      if (word.contains(keyword)) {
        return true;
      }
    }
    return false;
  }

  /**
   * 단일 이름 마스킹 규칙
   * - 2자: 이* (예: 이영 → 이*)
   * - 3자: 홍*동 (예: 홍길동 → 홍*동)
   * - 4자: 홍**동 (예: 홍길순동 → 홍**동)
   */
  private String maskSingleName(String bdst) {
    if (bdst == null || bdst.isEmpty()) {
      return "";
    }

    int length = bdst.length();

    switch (length) {
      case 2:
        return bdst.charAt(0) + "*";
      case 3:
        return bdst.charAt(0) + "*" + bdst.charAt(2);
      case 4:
        return bdst.charAt(0) + "**" + bdst.charAt(3);
      default:
        return bdst;
    }
  }
}
