package com.psg.dlsysinfo.dl_sysinfo_server.repository;

import com.psg.dlsysinfo.dl_sysinfo_server.dto.InstalledAppDTO;
import com.psg.dlsysinfo.dl_sysinfo_server.entity.Devices;
import com.psg.dlsysinfo.dl_sysinfo_server.entity.InstalledSoftware;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.query.Param;
import org.springframework.stereotype.Repository;

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

@Repository
public interface InstalledSoftwareRepository extends JpaRepository<InstalledSoftware, Long> {

    Optional<InstalledSoftware> findByDeviceAndAppName(Devices device, String appName);
    List<InstalledSoftware> findByDevice(Devices device);
    @Query("SELECT DISTINCT new com.psg.dlsysinfo.dl_sysinfo_server.dto.InstalledAppDTO(" +
           "s.appName, s.appVersion, s.publisher) " +
           "FROM InstalledSoftware s WHERE s.appName IS NOT NULL")
    List<InstalledAppDTO> findDistinctInstalledAppDTOs();


    @Query("""
    SELECT s FROM InstalledSoftware s
    JOIN s.device d
    WHERE d.client.clientId = :clientId
""")
    List<InstalledSoftware> findAllByClientId(Long clientId);

    @Query("""
    SELECT s FROM InstalledSoftware s
    JOIN FETCH s.device d
    JOIN FETCH d.client
""")
    List<InstalledSoftware> findAllWithDeviceAndClient();

    @Query("""
    SELECT s FROM InstalledSoftware s
    JOIN FETCH s.device d
    JOIN FETCH d.client c
    WHERE c.clientId = :clientId
""")
    List<InstalledSoftware> findAllByClientIdWithDevice(@Param("clientId") Long clientId);

}
