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

import io.gmss.fiscad.entities.infocad.metier.ParcelleGeom;
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 ParcelleGeomRepository extends JpaRepository<ParcelleGeom, Long> {

    List<ParcelleGeom> findAllByQuartier_Code(String code);

    Optional<ParcelleGeom> findFirstByNupProvisoire(String numProvisoir);
    @Modifying
    @Transactional
    @Query(value = "update parcelle_geom " +
            "set quartier_id=T.quartier_id " +
            "from " +
            "(select quartier.id as quartier_id,upper(quartier.nom) as nom_quartier,c.nom as nom_commune " +
            "from quartier inner join public.arrondissement a on a.id = quartier.arrondissement_id " +
            "inner join public.commune c on c.id = a.commune_id)T " +
            "where parcelle_geom.village_quartier=T.nom_quartier " +
            "and upper(parcelle_geom.commune)=upper(T.nom_commune) ",nativeQuery = true)
    void majIdQuartier();

    @Modifying
    @Transactional
    @Query(value = " UPDATE parcelle_geom" +
            " set geometry = " +
            " ST_SetSRID( " +
            "    ST_GeomFromText( geometry_string ), " +
            "    32631 " +
            "  )  ",nativeQuery = true)
    void creationGeometry();


//    @Query(value = "select id  " +
//            " from parcelle_geom " +
//            " where nup_provisoire = ?1 LIMIT 1 ",nativeQuery = true)
//    Long findFirstByNupProvisoire(String nupProvisoir);
    @Modifying
    @Transactional
    @Query(value = "update parcelle_geom " +
            " set statut_parcelle = 'ENQUETER_BATIE' " +
            " where nup_provisoire= ?1 ",nativeQuery = true)
    void majStatutParcelleGeomBatie(String nupProvisoire);
    @Modifying
    @Transactional
    @Query(value = "update parcelle_geom " +
            " set statut_parcelle = 'ENQUETER_NON_BATIE'  " +
            " where nup_provisoire= ?1 ",nativeQuery = true)
    void majStatutParcelleGeomNonBatie(String nupProvisoire);
    @Modifying
    @Transactional
    @Query(value = " update parcelle_geom " +
            " set statut_parcelle = 'NON_ENQUETER'  " +
            " where nup_provisoire= ?1 ",nativeQuery = true)
    void majStatutParcelleGeomNonEnqueter(String nupProvisoire);


    @Modifying
    @Transactional
    @Query(value = """
             update parcelle_geom
                set longitude=ST_X(ST_Transform(ST_Centroid(geometry), 4326)),
                        latitude=ST_Y(ST_Transform(ST_Centroid(geometry), 4326))
                where geometry is not null and (longitude is null or latitude is null);
            """,nativeQuery = true)
    void majCentroidParcelle();




}
