package tech.easyflow.common.filestorage.impl;

import org.dromara.x.file.storage.core.FileInfo;
import org.dromara.x.file.storage.core.recorder.FileRecorder;
import org.dromara.x.file.storage.core.upload.FilePartInfo;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.Date;

/**
 * 文件记录器（基于 Redis 存储上传记录，满足多实例共享）
 */
@Service
public class FileRecoderImpl implements FileRecorder {

    private static final Logger LOG = LoggerFactory.getLogger(FileRecoderImpl.class);
    private static final String FILE_RECORD_KEY_PREFIX = "easyflow:xfile:record:";

    @Autowired(required = false)
    private RedisTemplate<String, Object> redisTemplate;

    private String buildKey(String url) {
        return FILE_RECORD_KEY_PREFIX + url;
    }

    @Override
    public boolean save(FileInfo fileInfo) {
        if (fileInfo == null || !StringUtils.hasText(fileInfo.getUrl())) {
            return false;
        }
        if (fileInfo.getCreateTime() == null) {
            fileInfo.setCreateTime(new Date());
        }
        if (redisTemplate != null) {
            redisTemplate.opsForValue().set(buildKey(fileInfo.getUrl()), fileInfo);
        }
        return true;
    }

    @Override
    public void update(FileInfo fileInfo) {
        save(fileInfo);
    }

    @Override
    public FileInfo getByUrl(String url) {
        if (!StringUtils.hasText(url) || redisTemplate == null) {
            return null;
        }
        Object value = redisTemplate.opsForValue().get(buildKey(url));
        if (value == null) {
            return null;
        }
        if (value instanceof FileInfo) {
            return (FileInfo) value;
        }
        LOG.warn("FileInfo redis记录类型异常，url={}, class={}", url, value.getClass().getName());
        return null;
    }

    @Override
    public boolean delete(String url) {
        if (!StringUtils.hasText(url) || redisTemplate == null) {
            return false;
        }
        Boolean deleted = redisTemplate.delete(buildKey(url));
        return Boolean.TRUE.equals(deleted);
    }

    @Override
    public void saveFilePart(FilePartInfo filePartInfo) {
        // 当前业务未使用手动分片上传，不做持久化
    }

    @Override
    public void deleteFilePartByUploadId(String uploadId) {
        // 当前业务未使用手动分片上传，不做持久化
    }
}
