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

import io.gmss.fiscad.entities.infocad.metier.ActeurConcerne;
import io.gmss.fiscad.entities.infocad.parametre.Personne;
import io.gmss.fiscad.paylaods.response.restoration.ActeurConcernePayLoad;
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 ActeurConcerneRepository extends JpaRepository<ActeurConcerne, Long> {
    Optional<ActeurConcerne> findFirstByExternalKey(Long externalKey);
    Optional<ActeurConcerne> findByMobileDataId(Long id);
    List<ActeurConcerne> findActeurConcerneByEnquete_Id(Long EnqueteId);

    Optional<ActeurConcerne> findFirstByExternalKeyAndTerminal_Id(Long externalKey, Long terminalId);
    @Modifying
    @Transactional
    @Query(value = "delete from acteur_concerne ac  where ac.id in (select ac.id from enquete e" +
            "           inner join acteur_concerne ac on e.id = ac.enquete_id" +
            "           where e.id = ?1)", nativeQuery = true)
    void deleteActeurConcerneByEnquete(Long enqueteId);

    @Query(value = "SELECT ac.id as idBackend," +
            " ac.external_key as externalKey," +
            " ac.part," +
            " ac.type_droit as typeDroit," +
            " e.external_key as enqueteId," +
            " ac.position_representation_id as positionRepresentationId, " +
            " p.external_key as personneId, " +
            " ac.type_representation_id as typeRepresentationId, " +
            " ac.type_contestation_id as typeContestationId, " +
            " ac.role_acteur as roleActeur, " +
            " ac.synchronise, " +
            " ac.observation, " +
            " ac.terminal_id as terminalId, " +
            " ac.bloc_id as blocId, " +
            " ac.have_declarant as haveDeclarant, " +
            " ac.max_numero_acteur_concerne_id" +
            " FROM acteur_concerne ac inner join enquete e on e.id = ac.enquete_id inner join personne p on p.id = ac.personne_id " +
            " where ac.terminal_id = ?1 ", nativeQuery = true)
    List<ActeurConcernePayLoad> getActeurConcerneByTerminalId(Long terminalId);

}