package cn.reghao.oss.web.app.service;

import cn.reghao.jutil.jdk.result.Result;
import cn.reghao.oss.web.app.db.repository.StoreNodeRepository;
import cn.reghao.oss.web.app.model.dto.StoreNodeUpdateDto;
import cn.reghao.oss.web.app.model.po.StoreNode;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * @author reghao
 * @date 2024-02-23 13:01:38
 */
@Service
public class StoreNodeService {
    private final StoreNodeRepository storeNodeRepository;

    public StoreNodeService(StoreNodeRepository storeNodeRepository) {
        this.storeNodeRepository = storeNodeRepository;
    }

    public void add(StoreNode storeNode) {
        String ipv4 = storeNode.getIpv4Addr();
        StoreNode entity = storeNodeRepository.findByIpv4Addr(ipv4);
        if (entity == null) {
            storeNodeRepository.save(storeNode);
        }
    }

    public Result updateDomain(StoreNodeUpdateDto storeNodeUpdateDto) {
        int id = storeNodeUpdateDto.getId();
        StoreNode storeNode = storeNodeRepository.findById(id).orElse(null);
        if (storeNode == null) {
            return Result.fail(String.format("id %s not exist", id));
        }

        String domain = storeNodeUpdateDto.getDomain();
        StoreNode entity = storeNodeRepository.findByDomain(domain);
        if (entity != null) {
            return Result.fail(String.format("domain %s exist", domain));
        }

        if (domain.equals(storeNode.getDomain())) {
            return Result.success();
        }

        storeNode.setDomain(domain);
        storeNodeRepository.save(storeNode);
        return Result.success();
    }

    public Result delete(int nodeId) {
        StoreNode storeNode = storeNodeRepository.findById(nodeId).orElse(null);
        if (storeNode == null) {
            return Result.fail("node not exist");
        }

        //storeNodeRepository.delete(storeNode);
        return Result.success("not implement");
    }

    public StoreNode get() {
        List<StoreNode> list = storeNodeRepository.findAll();
        if (list.isEmpty()) {
            return null;
        }

        return list.get(0);
    }

    public List<StoreNode> getStoreNodes() {
        return storeNodeRepository.findAll();
    }
}
