package com.storycove.repository;

import com.storycove.entity.TagAlias;
import com.storycove.entity.Tag;
import org.springframework.data.jpa.repository.JpaRepository;
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;
import java.util.UUID;

@Repository
public interface TagAliasRepository extends JpaRepository<TagAlias, UUID> {
    
    /**
     * Find alias by exact alias name (case-insensitive)
     */
    @Query("SELECT ta FROM TagAlias ta WHERE LOWER(ta.aliasName) = LOWER(:aliasName)")
    Optional<TagAlias> findByAliasNameIgnoreCase(@Param("aliasName") String aliasName);
    
    /**
     * Find all aliases for a specific canonical tag
     */
    List<TagAlias> findByCanonicalTag(Tag canonicalTag);
    
    /**
     * Find all aliases for a specific canonical tag ID
     */
    @Query("SELECT ta FROM TagAlias ta WHERE ta.canonicalTag.id = :tagId")
    List<TagAlias> findByCanonicalTagId(@Param("tagId") UUID tagId);
    
    /**
     * Find aliases created from merge operations
     */
    List<TagAlias> findByCreatedFromMergeTrue();
    
    /**
     * Check if an alias name already exists
     */
    boolean existsByAliasNameIgnoreCase(String aliasName);
    
    /**
     * Delete all aliases for a specific tag
     */
    void deleteByCanonicalTag(Tag canonicalTag);
    
    /**
     * Count aliases for a specific tag
     */
    @Query("SELECT COUNT(ta) FROM TagAlias ta WHERE ta.canonicalTag.id = :tagId")
    long countByCanonicalTagId(@Param("tagId") UUID tagId);
    
    /**
     * Find aliases that start with the given prefix (case-insensitive)
     */
    @Query("SELECT ta FROM TagAlias ta WHERE LOWER(ta.aliasName) LIKE LOWER(CONCAT(:prefix, '%'))")
    List<TagAlias> findByAliasNameStartingWithIgnoreCase(@Param("prefix") String prefix);
}