package com.gnx.telemedicine.repository;

import com.gnx.telemedicine.model.Doctor;
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 DoctorRepository extends JpaRepository<Doctor, UUID> {
    Optional<Doctor> findByMedicalLicenseNumber(String medicalLicenseNumber);
    Optional<Doctor> findByUser(UserModel user);
    
    @Query("SELECT d FROM Doctor d JOIN FETCH d.user WHERE d.user.isActive IS NULL OR d.user.isActive = true")
    List<Doctor> findAllWithActiveUser();
    
    @Query("SELECT d FROM Doctor d JOIN FETCH d.user WHERE (d.user.isActive IS NULL OR d.user.isActive = true) AND " +
           "(LOWER(d.user.firstName) LIKE LOWER(CONCAT('%', :query, '%')) OR " +
           "LOWER(d.user.lastName) LIKE LOWER(CONCAT('%', :query, '%')) OR " +
           "LOWER(d.specialization) LIKE LOWER(CONCAT('%', :query, '%')))")
    List<Doctor> searchDoctors(@org.springframework.data.repository.query.Param("query") String query);
    
    // For chat search - return all doctors except explicitly deactivated ones
    @Query("SELECT d FROM Doctor d JOIN FETCH d.user WHERE (d.user.isActive IS NULL OR d.user.isActive = true)")
    List<Doctor> findAllForChat();
    
    @Query("SELECT d FROM Doctor d JOIN FETCH d.user WHERE (d.user.isActive IS NULL OR d.user.isActive = true) AND " +
           "(LOWER(d.user.firstName) LIKE LOWER(CONCAT('%', :query, '%')) OR " +
           "LOWER(d.user.lastName) LIKE LOWER(CONCAT('%', :query, '%')) OR " +
           "LOWER(d.specialization) LIKE LOWER(CONCAT('%', :query, '%')))")
    List<Doctor> searchDoctorsForChat(@org.springframework.data.repository.query.Param("query") String query);
    
    @Query("SELECT d FROM Doctor d JOIN FETCH d.user WHERE d.user.id IN :userIds")
    List<Doctor> findByUserIds(@org.springframework.data.repository.query.Param("userIds") List<UUID> userIds);
}
