package com.gnx.telemedicine.repository;

import com.gnx.telemedicine.model.Patient;
import com.gnx.telemedicine.model.UserModel;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.Query;
import org.springframework.stereotype.Repository;

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

@Repository
public interface PatientRepository extends JpaRepository<Patient, UUID> {
    Optional<Patient> findByUser(UserModel user);
    
    @Query("SELECT p FROM Patient p JOIN FETCH p.user WHERE p.user.isActive IS NULL OR p.user.isActive = true")
    List<Patient> findAllWithActiveUser();
    
    @Query("SELECT p FROM Patient p JOIN FETCH p.user WHERE (p.user.isActive IS NULL OR p.user.isActive = true) AND " +
           "(LOWER(p.user.firstName) LIKE LOWER(CONCAT('%', :query, '%')) OR " +
           "LOWER(p.user.lastName) LIKE LOWER(CONCAT('%', :query, '%')))")
    List<Patient> searchPatients(@org.springframework.data.repository.query.Param("query") String query);
    
    // For chat search - return all patients except explicitly deactivated ones
    @Query("SELECT p FROM Patient p JOIN FETCH p.user WHERE (p.user.isActive IS NULL OR p.user.isActive = true)")
    List<Patient> findAllForChat();
    
    @Query("SELECT p FROM Patient p JOIN FETCH p.user WHERE (p.user.isActive IS NULL OR p.user.isActive = true) AND " +
           "(LOWER(p.user.firstName) LIKE LOWER(CONCAT('%', :query, '%')) OR " +
           "LOWER(p.user.lastName) LIKE LOWER(CONCAT('%', :query, '%')))")
    List<Patient> searchPatientsForChat(@org.springframework.data.repository.query.Param("query") String query);
    
    @Query("SELECT p FROM Patient p JOIN FETCH p.user WHERE p.user.id IN :userIds")
    List<Patient> findByUserIds(@org.springframework.data.repository.query.Param("userIds") List<UUID> userIds);
}
