package com.ga.common.file;

import com.ga.common.exception.BizException;
import com.ga.common.exception.ErrorCode;
import com.ga.common.model.ApiResponse;
import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.servlet.http.HttpServletResponse;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.List;

@Tag(name = "파일")
@Slf4j
@RestController
@RequestMapping("/api/files")
@RequiredArgsConstructor
public class FileController {

    private final FileService service;

    @PostMapping
    public ApiResponse<FileVO> upload(@RequestParam MultipartFile file,
                                      @RequestParam(required = false, defaultValue = "default") String fileGroup) {
        return ApiResponse.ok(service.upload(file, fileGroup));
    }

    @GetMapping("/{fileId}")
    public void download(@PathVariable Long fileId, HttpServletResponse response) {
        FileVO vo = service.download(fileId);
        Path path = Paths.get(vo.getFilePath());
        if (!Files.exists(path)) throw new BizException(ErrorCode.FILE_NOT_FOUND);
        try {
            response.setContentType(vo.getContentType() != null ? vo.getContentType() : "application/octet-stream");
            String encoded = URLEncoder.encode(vo.getOriginalName(), StandardCharsets.UTF_8).replace("+", "%20");
            response.setHeader("Content-Disposition", "attachment; filename*=UTF-8''" + encoded);
            Files.copy(path, response.getOutputStream());
        } catch (IOException e) {
            log.error("File download error", e);
            throw new BizException(ErrorCode.INTERNAL_ERROR, "파일 다운로드 실패");
        }
    }

    @GetMapping("/groups/{fileGroup}")
    public ApiResponse<List<FileVO>> listByGroup(@PathVariable String fileGroup) {
        return ApiResponse.ok(service.listByGroup(fileGroup));
    }

    @DeleteMapping("/{fileId}")
    public ApiResponse<Void> delete(@PathVariable Long fileId) {
        service.delete(fileId);
        return ApiResponse.ok();
    }
}
