package com.erp.systemtool.repository;

import com.erp.systemtool.entity.SystemConfig;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.Modifying;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.query.Param;
import org.springframework.stereotype.Repository;

import java.util.List;
import java.util.Optional;

/**
 * Repository for SystemConfig entity
 */
@Repository
public interface SystemConfigRepository extends JpaRepository<SystemConfig, Long> {

    Optional<SystemConfig> findByTenantIdAndConfigGroupAndConfigKey(
            Integer tenantId, String configGroup, String configKey);

    List<SystemConfig> findByTenantIdAndConfigGroup(Integer tenantId, String configGroup);

    @Modifying
    @Query("UPDATE SystemConfig c SET c.configValue = :value, c.updatedAt = CURRENT_TIMESTAMP " +
           "WHERE c.tenantId = :tenantId AND c.configGroup = :group AND c.configKey = :key")
    int updateValue(@Param("tenantId") Integer tenantId,
                    @Param("group") String group,
                    @Param("key") String key,
                    @Param("value") String value);

    @Modifying
    @Query("DELETE FROM SystemConfig c WHERE c.createdAt < :cutoffDate")
    int deleteOlderThan(@Param("cutoffDate") java.time.LocalDateTime cutoffDate);
}
