package cn.reghao.tnb.file.app.zoss.db.repository;

import cn.reghao.tnb.oss.api.dto.StoreNodeDto;
import cn.reghao.tnb.file.app.zoss.db.mapper.StoreNodeMapper;
import cn.reghao.tnb.file.app.zoss.db.mapper.StoreVolumeMapper;
import cn.reghao.tnb.file.app.zoss.db.mapper.UploadChannelMapper;
import cn.reghao.tnb.file.app.zoss.model.po.StoreNode;
import cn.reghao.tnb.file.app.zoss.model.po.StoreVolume;
import cn.reghao.tnb.file.app.zoss.model.po.UploadChannel;
import cn.reghao.tnb.file.app.service.StoreConfigService;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Repository;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;
import java.util.stream.Collectors;

/**
 * @author reghao
 * @date 2025-10-17 09:14:47
 */
@Repository
public class StoreRepository {
    private final StoreNodeMapper storeNodeMapper;
    private final StoreVolumeMapper storeVolumeMapper;
    private final UploadChannelMapper uploadChannelMapper;
    private final StoreConfigService storeConfigService;

    public StoreRepository(StoreNodeMapper storeNodeMapper, StoreVolumeMapper storeVolumeMapper,
                           UploadChannelMapper uploadChannelMapper, StoreConfigService storeConfigService) {
        this.storeNodeMapper = storeNodeMapper;
        this.storeVolumeMapper = storeVolumeMapper;
        this.uploadChannelMapper = uploadChannelMapper;
        this.storeConfigService = storeConfigService;
    }

    @Transactional(rollbackFor = Exception.class)
    public int saveStoreNode(StoreNodeDto storeNodeDto) {
        StoreNode storeNode = new StoreNode(storeNodeDto);
        storeNodeMapper.save(storeNode);

        int storeNodeId = storeNode.getId();
        List<StoreVolume> storeVolumes = storeNodeDto.getDiskVolumes().stream()
                .map(diskVolume -> new StoreVolume(storeNodeId, diskVolume))
                .collect(Collectors.toList());
        if (!storeVolumes.isEmpty()) {
            storeVolumeMapper.saveAll(storeVolumes);
        }
        return storeNode.getId();
    }

    @Cacheable(cacheNames = "tnb:file:channel", key = "#ossUser + '_' + #channelName", unless = "#result == null")
    public UploadChannel getUploadChannel(int ossUser, String channelName) {
        return uploadChannelMapper.findByCreateByAndName(ossUser, channelName);
    }
}
