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

import io.gmss.fiscad.entities.infocad.parametre.Structure;
import io.gmss.fiscad.paylaods.response.ArrondissementEnqResponse;
import io.gmss.fiscad.paylaods.response.StructureEnqResponse;
import io.gmss.fiscad.paylaods.response.StructureResponse;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.Query;

import java.util.List;

public interface StructureRepository extends JpaRepository<Structure, Long> {
    boolean existsDistinctByCode(String code);

    @Query(value = "select max(id) as id from structure", nativeQuery = true)
    int getLastRecordId();

    @Query(value = "select s.id, s.code, s.nom, s.ifu, s.rccm, s.tel, s.email, s.adresse" +
            " from structure s inner join " +
            " arrondissements_structures sa on s.id = sa.structure_id and " +
            " sa.arrondissement_id = ?1", nativeQuery = true)
    List<StructureResponse> getStructureByArrondissement(Long arrondissementId);



    @Query(value = """
           select
           s.id,
           s.code,
           s.nom,
           c.id as communeId,
           count(distinct e.id) as nombreEnquete
           from structure s
           inner join commune c on c.id=s.commune_id
           left join bloc b on b.structure_id=s.id
           left join enquete e on e.bloc_id=b.id
           group by s.id,s.code,s.nom,c.id ;
           """, nativeQuery = true)
    List<StructureEnqResponse> getAdminStructureEnqResponse();


    @Query(value = """
           select
           s.id,
           s.code,
           s.nom,
           c.id as communeId,
           count(distinct e.id) as nombreEnquete
           from structure s
           inner join commune c on c.id=s.commune_id
           left join bloc b on b.structure_id=s.id
           left join enquete e on e.bloc_id=b.id
           where s.id= ?1
           group by s.id,s.code,s.nom,c.id ;
           """, nativeQuery = true)
    List<StructureEnqResponse> getStructureEnqResponse(Long structure_id);
}
