package incheon.com.file.web;

import incheon.com.file.service.ComFileService;
import incheon.com.file.vo.ComFileDtlVO;
import incheon.com.file.vo.ComFileSearchVO;
import incheon.com.file.vo.ComFileVO;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 공통 파일 REST API Controller
 * *
 * @since 2025.10.17
 */
@Slf4j
@RestController
@RequiredArgsConstructor
@Tag(name = "공통파일", description = "공통 파일 관리 API")
public class ComFileApiController {

    private final ComFileService comFileService;

    /**
     * 파일 그룹 목록 조회
     */
    @GetMapping("/api/v1/comfile")
    @Operation(summary = "파일 그룹 목록 조회", description = "파일 그룹 목록을 조회합니다")
    public ResponseEntity<Map<String, Object>> getFileGroupList(
            @ModelAttribute ComFileSearchVO searchVO) {

        List<ComFileVO> list = comFileService.selectComFileList(searchVO);
        int totalCount = comFileService.selectComFileListTotCnt(searchVO);

        Map<String, Object> result = new HashMap<>();
        result.put("list", list);
        result.put("totalCount", totalCount);

        return ResponseEntity.ok(result);
    }

    /**
     * 파일 그룹 상세 조회
     */
    @GetMapping("/api/v1/comfile/{atchFileId}")
    @Operation(summary = "파일 그룹 상세 조회", description = "파일 그룹 및 파일 목록을 조회합니다")
    public ResponseEntity<Map<String, Object>> getFileGroupDetail(
            @PathVariable @Parameter(description = "파일그룹ID") String atchFileId) {

        ComFileVO fileGroup = comFileService.selectComFileDetail(atchFileId);
        List<ComFileDtlVO> fileList = comFileService.selectComFileDtlList(atchFileId);

        Map<String, Object> result = new HashMap<>();
        result.put("fileGroup", fileGroup);
        result.put("fileList", fileList);

        return ResponseEntity.ok(result);
    }

    /**
     * 파일 상세 목록 조회
     */
    @GetMapping("/api/v1/comfile/{atchFileId}/files")
    @Operation(summary = "파일 상세 목록 조회", description = "파일 그룹의 파일 목록을 조회합니다")
    public ResponseEntity<List<ComFileDtlVO>> getFileList(
            @PathVariable @Parameter(description = "파일그룹ID") String atchFileId) {

        List<ComFileDtlVO> fileList = comFileService.selectComFileDtlList(atchFileId);
        return ResponseEntity.ok(fileList);
    }

    /**
     * 파일 업로드 (단일)
     */
    @PostMapping("/api/v1/comfile/upload")
    @Operation(summary = "파일 업로드", description = "파일을 임시로 업로드합니다")
    public ResponseEntity<Map<String, Object>> uploadFile(
            @RequestParam("file") @Parameter(description = "업로드할 파일") MultipartFile file,
            @RequestParam(value = "atchFileId", required = false) @Parameter(description = "기존 파일그룹ID") String atchFileId) {

        try {
            ComFileDtlVO uploadedFile = comFileService.uploadFile(file, atchFileId);

            Map<String, Object> result = new HashMap<>();
            result.put("success", true);
            result.put("atchFileId", uploadedFile.getAtchFileId());
            result.put("fileId", uploadedFile.getFileId());
            result.put("orgnlFileNm", uploadedFile.getOrgnlFileNm());
            result.put("fileSz", uploadedFile.getFileSz());
            result.put("mimeTypeNm", uploadedFile.getMimeTypeNm());

            return ResponseEntity.ok(result);

        } catch (IOException e) {
            log.error("파일 업로드 실패", e);
            Map<String, Object> error = new HashMap<>();
            error.put("success", false);
            error.put("message", "파일 업로드 실패: " + e.getMessage());
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(error);
        }
    }

    /**
     * 파일 업로드 (다중)
     */
    @PostMapping("/api/v1/comfile/upload/multiple")
    @Operation(summary = "다중 파일 업로드", description = "여러 파일을 임시로 업로드합니다")
    public ResponseEntity<Map<String, Object>> uploadFiles(
            @RequestParam("files") @Parameter(description = "업로드할 파일들") MultipartFile[] files,
            @RequestParam(value = "atchFileId", required = false) @Parameter(description = "기존 파일그룹ID") String atchFileId) {

        try {
            String resultAtchFileId = comFileService.uploadFiles(files, atchFileId);

            Map<String, Object> result = new HashMap<>();
            result.put("success", true);
            result.put("atchFileId", resultAtchFileId);
            result.put("fileCount", files.length);

            return ResponseEntity.ok(result);

        } catch (IOException e) {
            log.error("파일 업로드 실패", e);
            Map<String, Object> error = new HashMap<>();
            error.put("success", false);
            error.put("message", "파일 업로드 실패: " + e.getMessage());
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(error);
        }
    }

    /**
     * 임시 파일을 정식 파일로 전환
     */
    @PutMapping("/api/v1/comfile/confirm")
    @Operation(summary = "파일 확정", description = "임시 파일을 정식 파일로 전환합니다")
    public ResponseEntity<Map<String, Object>> confirmFiles(
            @RequestParam @Parameter(description = "파일그룹ID") String atchFileId,
            @RequestParam @Parameter(description = "대상키명") String trgtNm) {

        comFileService.confirmFiles(atchFileId, trgtNm);

        Map<String, Object> result = new HashMap<>();
        result.put("success", true);
        result.put("message", "파일이 정식으로 등록되었습니다");

        return ResponseEntity.ok(result);
    }

    /**
     * 파일 삭제 (논리 삭제)
     */
    @DeleteMapping("/api/v1/comfile/dtl/{fileId}")
    @Operation(summary = "파일 삭제", description = "개별 파일을 삭제합니다 (논리 삭제)")
    public ResponseEntity<Map<String, Object>> deleteFile(
            @PathVariable @Parameter(description = "파일ID") String fileId) {

        comFileService.deleteFile(fileId);

        Map<String, Object> result = new HashMap<>();
        result.put("success", true);
        result.put("message", "파일이 삭제되었습니다");

        return ResponseEntity.ok(result);
    }

    /**
     * 파일 그룹 삭제 (물리 삭제)
     */
    @DeleteMapping("/api/v1/comfile/{atchFileId}")
    @Operation(summary = "파일 그룹 삭제", description = "파일 그룹 전체를 삭제합니다 (물리 삭제)")
    public ResponseEntity<Map<String, Object>> deleteFileGroup(
            @PathVariable @Parameter(description = "파일그룹ID") String atchFileId) {

        comFileService.deleteFileGroup(atchFileId);

        Map<String, Object> result = new HashMap<>();
        result.put("success", true);
        result.put("message", "파일 그룹이 삭제되었습니다");

        return ResponseEntity.ok(result);
    }

    /**
     * 파일 정렬 순서 변경
     */
    @PutMapping("/api/v1/comfile/dtl/{fileId}/sort")
    @Operation(summary = "파일 정렬 순서 변경", description = "파일의 정렬 순서를 변경합니다")
    public ResponseEntity<Map<String, Object>> updateFileSortSeq(
            @PathVariable @Parameter(description = "파일ID") String fileId,
            @RequestParam @Parameter(description = "정렬순서") Integer sortSeq) {

        comFileService.updateFileSortSeq(fileId, sortSeq);

        Map<String, Object> result = new HashMap<>();
        result.put("success", true);
        result.put("message", "정렬 순서가 변경되었습니다");

        return ResponseEntity.ok(result);
    }

    /**
     * 파일 개수 조회
     */
    @GetMapping("/api/v1/comfile/api/v1/comfile/{atchFileId}/count")
    @Operation(summary = "파일 개수 조회", description = "파일 그룹의 파일 개수를 조회합니다")
    public ResponseEntity<Map<String, Object>> getFileCount(
            @PathVariable @Parameter(description = "파일그룹ID") String atchFileId) {

        List<ComFileDtlVO> fileList = comFileService.selectComFileDtlList(atchFileId);

        Map<String, Object> result = new HashMap<>();
        result.put("count", fileList.size());
        result.put("atchFileId", atchFileId);

        return ResponseEntity.ok(result);
    }
}

