package com.example.todolist.controller;

import java.nio.charset.StandardCharsets;

import org.springframework.core.io.Resource;
import org.springframework.http.ContentDisposition;
import org.springframework.http.HttpHeaders;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RestController;

import com.example.todolist.service.DownloadService;
import com.example.todolist.service.FileDownload;

import lombok.RequiredArgsConstructor;

@RestController
@RequiredArgsConstructor
public class DownloadController {
    private final DownloadService downloadService;

    // 添付ファイルのダウンロード処理
    @GetMapping("/todo/af/download/{afId}")
    public ResponseEntity<Resource> downloadAttachedFile(@PathVariable int afId) {
        FileDownload r = downloadService.loadAsResource(afId);

        ContentDisposition cd = r.isInline()
                // ②-1 別タブ表示の場合
                ? ContentDisposition
                        .inline().filename(r.getFileName(), StandardCharsets.UTF_8).build()
                // ②-2 ダウンロードの場合
                : ContentDisposition
                        .attachment().filename(r.getFileName(), StandardCharsets.UTF_8).build();

        return ResponseEntity.ok()
                .contentType(r.getContentType())
                .header(HttpHeaders.CONTENT_DISPOSITION, cd.toString())
                .contentLength(r.getLength())
                .body(r.getResource());
    }
}
