package com.example.PhotoGallery.Repos;

import java.util.List;

import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
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 com.example.PhotoGallery.Models.Photo;

@Repository
public interface PhotoRepo extends JpaRepository<Photo, Long> {
    
    boolean existsByFileName(String fileName);

    @Query(value = "SELECT file_name FROM photos", nativeQuery = true)
    List<String> getAllFileNames();

    @Query(value = "SELECT * FROM photos ORDER BY id DESC", nativeQuery = true)
    Page<Photo> getPagedPhotos(Pageable pageable);

    @Query(value = "SELECT * FROM photos ORDER BY RAND() LIMIT :numRecords", nativeQuery = true)
    List<Photo> getRandomPhotos(@Param("numRecords") int numRandRecords);

    @Query(value = """
            SELECT DISTINCT p.*
    FROM photos p
    LEFT JOIN photo_tags pt ON pt.photo_id = p.id
    WHERE
        CONCAT_WS(' ',
            p.colour_space,
            p.copy_right,
            p.file_name,
            p.file_size,
            p.height,
            p.mime_type,
            p.title,
            p.description,
            p.width
        ) LIKE CONCAT('%', :searchValue, '%')
        OR pt.tag LIKE CONCAT('%', :searchValue, '%')
            """, nativeQuery = true)
    List<Photo> searchPhotos(@Param("searchValue") String searchValue);

    @Query(value = "SELECT * FROM photos WHERE id NOT IN (:ids) ORDER BY id DESC", nativeQuery = true)
    Page<Photo> findAllExpect(@Param("ids") List<Long> ids, Pageable pageable);

}