package com.qqchen.deploy.backend.notification.repository;

import com.qqchen.deploy.backend.framework.repository.IBaseRepository;
import com.qqchen.deploy.backend.notification.entity.NotificationTemplate;
import com.qqchen.deploy.backend.notification.enums.NotificationChannelTypeEnum;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
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接口
 *
 * @author qqchen
 * @since 2025-11-12
 */
@Repository
public interface INotificationTemplateRepository extends IBaseRepository<NotificationTemplate, Long> {

    /**
     * 根据编码查找模板
     */
    Optional<NotificationTemplate> findByCode(String code);

    /**
     * 根据编码和启用状态查找模板
     */
    Optional<NotificationTemplate> findByCodeAndEnabled(String code, Boolean enabled);


    @Query("SELECT t FROM NotificationTemplate t WHERE t.id = :id AND t.enabled = :enabled AND t.deleted = false")
    Optional<NotificationTemplate> findByIdAndEnabled(@Param("id") Long id, @Param("enabled") Boolean enabled);


    /**
     * 根据渠道类型查找模板
     */
    List<NotificationTemplate> findByChannelTypeAndEnabled(NotificationChannelTypeEnum channelType, Boolean enabled);

    /**
     * 检查编码是否存在（排除指定ID）
     */
    @Query("SELECT COUNT(t) > 0 FROM NotificationTemplate t WHERE t.code = :code AND t.id != :id")
    boolean existsByCodeAndIdNot(@Param("code") String code, @Param("id") Long id);

    /**
     * 分页查询模板
     */
    @Query("SELECT t FROM NotificationTemplate t WHERE " +
        "(:name IS NULL OR t.name LIKE %:name%) AND " +
        "(:code IS NULL OR t.code LIKE %:code%) AND " +
        "(:channelType IS NULL OR t.channelType = :channelType) AND " +
        "(:enabled IS NULL OR t.enabled = :enabled)")
    Page<NotificationTemplate> findByConditions(
        @Param("name") String name,
        @Param("code") String code,
        @Param("channelType") NotificationChannelTypeEnum channelType,
        @Param("enabled") Boolean enabled,
        Pageable pageable
    );
}
