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

import io.gmss.fiscad.entities.infocad.metier.Enquete;
import io.gmss.fiscad.entities.infocad.metier.Tpe;
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 org.springframework.data.repository.query.Param;

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

public interface TpeRepository extends JpaRepository<Tpe, Long> {

    Optional<Tpe> findDistinctByIdentifier(String identifier);

    List<Tpe> findAllByModel(String model);

    boolean existsDistinctByIdentifier(String identifier);

    boolean existsDistinctByCodeEquipe(String code);

    //List<Tpe> findAllByEnquetesIn(List<Enquete> enquetes);

    @Query(value = "select distinct tpe.* " +
            "from tpe inner join enquete e on e.terminal_id=tpe.id " +
            " where e.user_id = ?1", nativeQuery = true)
    List<Tpe> getTpeByUserId(Long userId);

    @Modifying
    @Transactional
    @Query(value = """
        INSERT INTO tpe (
            id,
            numero_equipement,
            identifier,
            model,
            code_equipe,
            deleted
        ) VALUES (
            :id,
            :numeroEquipement,
            :identifier,
            :model,
            :codeEquipe,
            false
        )
        """, nativeQuery = true)
    void insertTpeManuellement(
            @Param("id") Long id,
            @Param("numeroEquipement") String numeroEquipement,
            @Param("identifier") String identifier,
            @Param("model") String model,
            @Param("codeEquipe") String codeEquipe
    );
}