package kr.co.accura.wbx.spring.file;

import kr.co.accura.wbx.spring.common.BusinessException;
import kr.co.accura.wbx.spring.common.NotFoundException;
import kr.co.accura.wbx.spring.config.WbxSpringProperties;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.UUID;

@Slf4j
@Service
@RequiredArgsConstructor
@ConditionalOnProperty(name = "wbx.spring.file.storage-type", havingValue = "local", matchIfMissing = true)
public class LocalFileStorageService implements FileStorageService {

    private final WbxSpringProperties props;

    @Override
    public String upload(MultipartFile file, String category) {
        try {
            Path dir = Paths.get(props.getFile().getUploadDir(), category);
            Files.createDirectories(dir);

            String ext = getExtension(file.getOriginalFilename());
            String storedName = UUID.randomUUID() + (ext.isEmpty() ? "" : "." + ext);
            Path target = dir.resolve(storedName);

            file.transferTo(target.toFile());
            log.info("File uploaded: {} → {}", file.getOriginalFilename(), target);

            return category + "/" + storedName;
        } catch (IOException e) {
            throw new BusinessException("File upload failed: " + e.getMessage());
        }
    }

    @Override
    public byte[] download(String fileKey) {
        try {
            Path path = Paths.get(props.getFile().getUploadDir(), fileKey);
            if (!Files.exists(path)) {
                throw new NotFoundException("File not found: " + fileKey);
            }
            return Files.readAllBytes(path);
        } catch (IOException e) {
            throw new BusinessException("File download failed: " + e.getMessage());
        }
    }

    @Override
    public void delete(String fileKey) {
        try {
            Path path = Paths.get(props.getFile().getUploadDir(), fileKey);
            Files.deleteIfExists(path);
        } catch (IOException e) {
            log.warn("File delete failed: {}", e.getMessage());
        }
    }

    private String getExtension(String filename) {
        if (filename == null) return "";
        int dot = filename.lastIndexOf('.');
        return dot > 0 ? filename.substring(dot + 1).toLowerCase() : "";
    }
}
