package io.gmss.fiscad.repositories.infocad.metier;

import io.gmss.fiscad.entities.infocad.metier.Piece;
import io.gmss.fiscad.entities.infocad.parametre.Personne;
import io.gmss.fiscad.paylaods.response.restoration.PiecePayLoad;
import jakarta.transaction.Transactional;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.Modifying;
import org.springframework.data.jpa.repository.Query;

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

public interface PieceRepository extends JpaRepository<Piece, Long> {
    Optional<Piece> findFirstByExternalKeyAndTerminal_Id(Long externalKey, Long terminalId);
    @Query(nativeQuery = true, value = "delete from piece p  where p.id in (select p.id " +
            "                                                from piece p inner join acteur_concerne a on a.id = p.acteur_concerne_id" +
            "                                                inner join enquete e on e.id = a.enquete_id" +
            "                                                where e.id = ?1)")
    @Modifying
    @Transactional
    void deletePieceByEnqueteId(Long enqueteId);

    @Modifying
    @Transactional
    void deletePieceByPersonne_Id(Long personneId);

    @Query(value = "Select  " +
            " p.id as idBackend, " +
            " p.external_key as externalKey, " +
            " ac.external_key as acteurConcerneId, " +
            " p.date_expiration as dateExpiration," +
            " p.numero_piece as numeroPiece," +
            " p.url," +
            " p.type_piece_id as typePieceId, " +
            " pp.external_key as personneId, " +
            " p.acteur_concerne_id, " +
            " p.source_droit_id as sourceDroitId, " +
            " p.mode_acquisition_id as modeAcquisitionId, " +
            " p.enquete_id as enqueteId, " +
            " p.membre_groupe_id as membreGroupeId, " +
            " p.observation as Observation," +
            " p.synchronise," +
            " p.terminal_id as terminalId, " +

            " p.max_numero_piece_id, " +
            " p.max_numero_acteur_concerne_id, " +
            " p.bloc_id as blocId " +
            " from piece p left join personne pp on p.personne_id = pp.id left join acteur_concerne ac on ac.id = p.personne_id " +
            " where p.terminal_id = ?1"
            , nativeQuery = true)
    List<PiecePayLoad> getPiecesByTerminalId(Long terminalId);
    List<Piece> findByPersonne_Id(Long id);
    Optional<Piece> findByMobileDataId(Long id);
    List<Piece> findByPersonne_IdAndActeurConcerneIsNull(Long id);

}

