package ru.soune.nocopy.service.file;

import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.core.io.Resource;
import org.springframework.core.io.UrlResource;
import org.springframework.stereotype.Service;

import java.io.FileNotFoundException;
import java.io.IOException;
import java.nio.file.Path;
import java.nio.file.Paths;

@Service
@Slf4j
public class FileStorageService {

    @Value("${file.storage.base-path}")
    private String basePath;

    public Resource loadFileAsResource(String filePath) throws IOException {
        Path path = Paths.get(basePath).resolve(filePath).normalize();
        Resource resource = new UrlResource(path.toUri());

        if (!resource.exists()) {
            throw new FileNotFoundException("File not found: " + filePath);
        }

        if (!resource.isReadable()) {
            throw new IOException("File is not readable: " + filePath);
        }

        return resource;
    }
}
