package org.xyzh.file.strategy.impl;

import lombok.extern.slf4j.Slf4j;
import org.springframework.web.multipart.MultipartFile;
import org.xyzh.file.strategy.FileStorageStrategy;

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

/**
 * @description 本地文件存储策略实现
 * @filename LocalFileStorageStrategy.java
 * @author yslg
 * @copyright xyzh
 * @since 2025-10-16
 */
@Slf4j
public class LocalFileStorageStrategy implements FileStorageStrategy {

    private final String basePath;
    private final String urlPrefix;

    public LocalFileStorageStrategy(String basePath, String urlPrefix) {
        this.basePath = basePath;
        this.urlPrefix = urlPrefix;
        log.info("初始化本地存储策略: basePath={}, urlPrefix={}", basePath, urlPrefix);
    }

    @Override
    public String upload(MultipartFile file, String fileName, String module) throws IOException {
        // 创建模块目录
        String modulePath = basePath + File.separator + module;
        File moduleDir = new File(modulePath);
        if (!moduleDir.exists()) {
            moduleDir.mkdirs();
        }

        // 保存文件
        String filePath = modulePath + File.separator + fileName;
        Path path = Paths.get(filePath);
        Files.write(path, file.getBytes());

        log.info("文件上传成功，本地路径: {}", filePath);
        return module + "/" + fileName;
    }

    @Override
    public byte[] download(String filePath) throws IOException {
        Path path = Paths.get(basePath + File.separator + filePath);
        if (!Files.exists(path)) {
            throw new IOException("文件不存在: " + filePath);
        }
        return Files.readAllBytes(path);
    }

    @Override
    public boolean delete(String filePath) throws IOException {
        Path path = Paths.get(basePath + File.separator + filePath);
        if (Files.exists(path)) {
            Files.delete(path);
            log.info("文件删除成功: {}", filePath);
            return true;
        }
        return false;
    }

    @Override
    public String getFileUrl(String filePath) {
        return urlPrefix + "/" + filePath;
    }

    @Override
    public String getStorageType() {
        return "local";
    }
}

