package cn.meowrain.aioj.backend.fileservice.storage.impl;

import cn.meowrain.aioj.backend.fileservice.storage.FileStorageStrategy;
import cn.hutool.core.io.FileUtil;
import jakarta.annotation.PostConstruct;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.io.InputStream;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.StandardCopyOption;

/**
 * 本地文件存储策略
 *
 * @author meowrain
 * @since 2026-01-10
 */
@Slf4j
@Component("localFileStorageStrategy")
@RequiredArgsConstructor
public class LocalFileStorageStrategy implements FileStorageStrategy {

    @Value("${file-config.local.base-path:uploads}")
    private String basePath;

    @Value("${file-config.local.domain:http://localhost:10013/api}")
    private String domain;

    @Value("${file-config.local.url-prefix:/file}")
    private String urlPrefix;

    @PostConstruct
    public void init() {
        try {
            Path baseDir = Paths.get(basePath);
            if (!Files.exists(baseDir)) {
                Files.createDirectories(baseDir);
                log.info("创建本地文件存储目录: {}", basePath);
            }
        } catch (IOException e) {
            log.error("创建本地文件存储目录失败: {}", basePath, e);
            throw new RuntimeException("初始化本地文件存储失败", e);
        }
    }

    @Override
    public String upload(MultipartFile file, String filePath) throws IOException {
        Path targetPath = Paths.get(basePath, filePath);
        Path parentDir = targetPath.getParent();

        if (parentDir != null && !Files.exists(parentDir)) {
            Files.createDirectories(parentDir);
        }

        Files.copy(file.getInputStream(), targetPath, StandardCopyOption.REPLACE_EXISTING);
        log.info("文件上传成功: {}", targetPath);

        return getFileUrl(filePath);
    }

    @Override
    public String upload(InputStream inputStream, String filePath, long fileSize) throws IOException {
        Path targetPath = Paths.get(basePath, filePath);
        Path parentDir = targetPath.getParent();

        if (parentDir != null && !Files.exists(parentDir)) {
            Files.createDirectories(parentDir);
        }

        Files.copy(inputStream, targetPath, StandardCopyOption.REPLACE_EXISTING);
        log.info("文件流上传成功: {}", targetPath);

        return getFileUrl(filePath);
    }

    @Override
    public boolean delete(String filePath) {
        try {
            Path targetPath = Paths.get(basePath, filePath);
            if (Files.exists(targetPath)) {
                Files.delete(targetPath);
                log.info("文件删除成功: {}", targetPath);
                return true;
            }
            return false;
        } catch (IOException e) {
            log.error("文件删除失败: {}", filePath, e);
            return false;
        }
    }

    @Override
    public boolean exists(String filePath) {
        Path targetPath = Paths.get(basePath, filePath);
        return Files.exists(targetPath);
    }

    @Override
    public String getFileUrl(String filePath) {
        // 确保URL中始终使用正斜杠
        String normalizedPath = filePath.replace("\\", "/");
        return domain + urlPrefix + "/" + normalizedPath;
    }

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