package es.uv.saic.domain;

import java.util.List;

import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.Modifying;
import org.springframework.data.jpa.repository.Query;
import org.springframework.stereotype.Repository;
import org.springframework.transaction.annotation.Transactional;

@Repository
public interface DocumentRepository  extends JpaRepository<Document, Integer> {
	
	@Query(value="SELECT * FROM documents WHERE id_categoria = ?1 AND ((lugar = ?2 AND tlugar = ?3) OR lugar = 0) AND visible LIMIT 1;", nativeQuery=true)
	Document findByCategoriaOrgan(Integer categoria, Integer lugar, String tlugar); 
	
	@Query(value="SELECT * FROM documents WHERE id_categoria = ?1 AND ((lugar = ?2 AND tlugar = ?3) OR lugar = 0) AND visible", nativeQuery=true)
	List<Document> findAllByCategoriaOrgan(Integer categoria, Integer lugar, String tlugar);
	
	@Query(value="SELECT * FROM documents d LEFT JOIN categories c ON d.id_categoria = c.id_categoria WHERE c.nom_val = ?1 AND visible", nativeQuery=true)
	List<Document> findByCategoriaNom(String nom); 
	
	@Query(value="SELECT * FROM documents d LEFT JOIN categories c ON d.id_categoria = c.id_categoria WHERE c.tipus = ?1 AND visible", nativeQuery=true)
	List<Document> findByCategoriaTipus(String tipus); 
	
	@Transactional
    @Modifying(flushAutomatically = true, clearAutomatically = true)
	@Query(value="UPDATE documents SET visible = false WHERE lugar = ?1 AND tlugar = ?2", nativeQuery=true)
	void archiveByOrgan(Integer lugar, String tlugar);

}
