package io.gmss.fiscad.repositories.decoupage;

import io.gmss.fiscad.entities.decoupage.Arrondissement;
import io.gmss.fiscad.entities.decoupage.Commune;
import io.gmss.fiscad.paylaods.response.ArrondissementEnqResponse;
import io.gmss.fiscad.paylaods.response.ArrondissementSyncResponse;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.Query;

import java.util.List;

public interface ArrondissementRepository extends JpaRepository<Arrondissement, Long> {
    List<Arrondissement> findAllByCommune(Commune commune);

    @Query(value = "select a.id,code, nom,longitude,latitude, a.commune_id as communeId from arrondissement a" +
            " inner join arrondissements_structures sa on sa.arrondissement_id=a.id" +
            " where a.deleted is false and sa.structure_id = ?1 ", nativeQuery = true)
    List<ArrondissementSyncResponse> getArrondissementResponse(Long structure_id);

    @Query(value = "Select distinct  T.id,T.code, T.libelle,T.longitude,T.latitude, T.communeId, sum(case when T.enqueteId is null then 0 else 1 end) as nombreEnquete " +
            " From (select a.id,a.code, a.nom as libelle,a.longitude,a.latitude, a.commune_id as communeId, e.id as enqueteId from arrondissement a" +
            " left join bloc b on b.arrondissement_id=a.id " +
            " left join (select ee.id, ee.bloc_id, ee.status_enquete from enquete ee where ee.status_enquete in ('FINALISE','REJETE', 'VALIDE')) e on e.bloc_id=b.id)T " +
            " group by T.id,T.code, T.libelle,T.longitude,T.latitude, T.communeId ", nativeQuery = true)
    List<ArrondissementEnqResponse> getAdminArrondissementEnqResponse();


    @Query(value = "Select  T.id,T.code, T.libelle,T.longitude,T.latitude, T.communeId, sum(case when T.enqueteId is null then 0 else 1 end) as nombreEnquete " +
            " From (select distinct a.id,a.code, a.nom as libelle,a.longitude,a.latitude, a.commune_id as communeId, e.id as enqueteId from arrondissement a" +
            " inner join arrondissements_structures sa on sa.arrondissement_id=a.id " +
            " left join bloc b on b.arrondissement_id=a.id " +
            " left join (select ee.id, ee.bloc_id, ee.status_enquete from enquete ee where ee.status_enquete in ('FINALISE','REJETE', 'VALIDE')) e on e.bloc_id=b.id" +
            " where sa.structure_id = ?1  )T " +
            " group by T.id,T.code, T.libelle,T.longitude,T.latitude, T.communeId ", nativeQuery = true)
    List<ArrondissementEnqResponse> getArrondissementEnqResponse(Long structure_id);
}
