// TODO 미사용시작
package com.kamco.cd.training.common.download;

import com.kamco.cd.training.common.download.dto.DownloadSpec;
import com.kamco.cd.training.common.utils.UserUtil;
import java.io.IOException;
import java.io.InputStream;
import java.nio.file.Files;
import lombok.RequiredArgsConstructor;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;
import org.springframework.web.servlet.mvc.method.annotation.StreamingResponseBody;

@Service
@RequiredArgsConstructor
public class DownloadExecutor {

  private final UserUtil userUtil;

  public ResponseEntity<StreamingResponseBody> stream(DownloadSpec spec) throws IOException {

    if (!Files.isReadable(spec.filePath())) {
      return ResponseEntity.notFound().build();
    }

    StreamingResponseBody body =
        os -> {
          try (InputStream in = Files.newInputStream(spec.filePath())) {
            in.transferTo(os);
            os.flush();
          } catch (Exception e) {
            // 고용량은 중간 끊김 흔하니까 throw 금지
          }
        };

    String fileName =
        spec.downloadName() != null
            ? spec.downloadName()
            : spec.filePath().getFileName().toString();

    return ResponseEntity.ok()
        .contentType(
            spec.contentType() != null ? spec.contentType() : MediaType.APPLICATION_OCTET_STREAM)
        .header(HttpHeaders.CONTENT_DISPOSITION, "attachment; filename=\"" + fileName + "\"")
        .body(body);
  }
}
// TODO 미사용 끝
