package incheon.product.geoview2d.download.web;

import incheon.com.cmm.api.DefaultApiResponse;
import incheon.com.cmm.exception.BusinessException;
import incheon.product.geoview2d.download.service.SpatialDownloadService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import java.util.List;
import java.util.Set;

/**
 * 공간 데이터 다운로드 REST API 컨트롤러.
 *
 * 엔드포인트:
 *   - /api/v1/product/g2d/download  (다운로드)
 */
@Slf4j
@RestController
@RequestMapping("/api/v1/product/g2d/download")
public class DownloadApiController {

    private static final Set<String> ALLOWED_FORMATS = Set.of("shapefile", "csv", "excel", "dxf", "geojson");
    private static final Set<String> ALLOWED_LAYER_TYPES = Set.of("TASK", "USER");

    @Resource(name = "productSpatialDownloadService")
    private SpatialDownloadService spatialDownloadService;

    /**
     * 레이어 데이터 다운로드.
     *
     * @param layerId   레이어 ID
     * @param layerType 레이어 유형 (TASK / USER, 기본값: TASK)
     * @param format    포맷 (shapefile, csv, excel, dxf, geojson)
     * @param columns   컬럼 목록 (쉼표 구분, 선택)
     */
    @GetMapping
    public ResponseEntity<org.springframework.core.io.Resource> download(
            @RequestParam Long layerId,
            @RequestParam(defaultValue = "TASK") String layerType,
            @RequestParam String format,
            @RequestParam(required = false) String columns) {

        if (!ALLOWED_LAYER_TYPES.contains(layerType.toUpperCase())) {
            throw new BusinessException("허용되지 않는 레이어 유형: " + layerType, HttpStatus.BAD_REQUEST);
        }
        if (!ALLOWED_FORMATS.contains(format.toLowerCase())) {
            throw new BusinessException("허용되지 않는 포맷: " + format, HttpStatus.BAD_REQUEST);
        }
        log.info("다운로드 요청 - layerId: {}, layerType: {}, format: {}", layerId, layerType, format);
        return spatialDownloadService.download(layerId, layerType, format, columns);
    }

    /**
     * 지원 포맷 목록.
     */
    @GetMapping("/formats")
    public ResponseEntity<DefaultApiResponse<List<String>>> getSupportedFormats() {
        return ResponseEntity.ok(DefaultApiResponse.success(
                List.of("shapefile", "csv", "excel", "dxf", "geojson")));
    }
}
