package com.example.todolist.service;

import java.io.File;
import java.nio.file.Files;
import java.nio.file.Path;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.core.io.FileSystemResource;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Service;

import com.example.todolist.common.Utils;
import com.example.todolist.entity.AttachedFile;
import com.example.todolist.exception.NotFoundException;
import com.example.todolist.repository.AttachedFileRepository;

import lombok.RequiredArgsConstructor;

@Service
@RequiredArgsConstructor
public class DownloadService {
    private final AttachedFileRepository attachedFileRepository;

    @Value("${attached.file.path}")
    private String ATTACHED_FILE_PATH;

    public FileDownload loadAsResource(int afId) {
        // 添付ファイル情報取得
        AttachedFile af = attachedFileRepository.findById(afId)
                .orElseThrow(() -> new NotFoundException("msg.e.attached_file_not_found", afId));

        // ファイルパス → Resource
        String fileName = af.getFileName();
        String downLoadFilePath = Utils.makeAttahcedFilePath(ATTACHED_FILE_PATH, af);
        File file = new File(downLoadFilePath);
        if (!file.exists() || !file.isFile()) {
            throw new NotFoundException("msg.e.attached_file_body_not_found", afId);
        }
        FileSystemResource resource = new FileSystemResource(file);

        // inline判定
        boolean inline = Utils.isInlineDisplayable(fileName);

        // Content-Type決定
        MediaType contentType = MediaType.APPLICATION_OCTET_STREAM;
        try {
            String probed = Files.probeContentType(Path.of(downLoadFilePath));
            if (probed != null && !probed.isBlank()) {
                contentType = MediaType.parseMediaType(probed);
            }
        } catch (Exception ignore) {
            // フォールバックは octet-stream
        }

        // ファイルサイズ
        long length;
        try {
            length = Files.size(Path.of(downLoadFilePath));
        } catch (Exception e) {
            length = file.length();
        }

        // FileDownloadにまとめて返す
        return new FileDownload(resource, fileName, contentType, length, inline);
    }
}
