package cn.reghao.bnt.web.admin.db.repository;

import cn.reghao.bnt.web.admin.model.po.SiteOption;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.stereotype.Service;

/**
 * @author reghao
 * @date 2025-10-14 08:49:53
 */
@Service
public class SiteOptionRepo {
    private final int pageSize = 100;
    private final SiteOptionRepository siteOptionRepository;

    public SiteOptionRepo(SiteOptionRepository siteOptionRepository) {
        this.siteOptionRepository = siteOptionRepository;
    }

    @CacheEvict(cacheNames = "siteOptions", key = "#newSiteOption.getPropKey()")
    public void updateSiteOption(SiteOption newSiteOption) {
        SiteOption siteOption1 = siteOptionRepository.findByPropKey(newSiteOption.getPropKey());
        if (siteOption1 != null && !siteOption1.getPropValue().equals(newSiteOption.getPropValue())) {
            siteOption1.setPropValue(newSiteOption.getPropValue());
            siteOptionRepository.save(siteOption1);
        }
    }

    @Cacheable(cacheNames = "siteOptions", key = "#propKey", unless = "#result == null")
    public String getPropValue(String propKey) {
        SiteOption siteOption = siteOptionRepository.findByPropKey(propKey);
        return siteOption.getPropValue();
    }

    public Page<SiteOption> getAll() {
        PageRequest pageRequest = PageRequest.of(0, pageSize);
        Page<SiteOption> page = siteOptionRepository.findAll(pageRequest);
        return page;
    }
}
