package com.gnx.telemedicine.repository;

import com.gnx.telemedicine.model.Prescription;
import com.gnx.telemedicine.model.enums.PrescriptionStatus;
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.time.LocalDate;
import java.util.List;
import java.util.Optional;
import java.util.UUID;

@Repository
public interface PrescriptionRepository extends JpaRepository<Prescription, UUID> {
    
    List<Prescription> findByPatientIdOrderByCreatedAtDesc(UUID patientId);
    
    List<Prescription> findByPatientIdAndStatusOrderByCreatedAtDesc(UUID patientId, PrescriptionStatus status);
    
    List<Prescription> findByDoctorIdOrderByCreatedAtDesc(UUID doctorId);
    
    List<Prescription> findByAppointmentId(UUID appointmentId);
    
    Optional<Prescription> findByPrescriptionNumber(String prescriptionNumber);
    
    @Query("SELECT p FROM Prescription p WHERE p.patient.id = :patientId AND p.status = 'ACTIVE' AND p.endDate >= :currentDate ORDER BY p.startDate ASC")
    List<Prescription> findActivePrescriptionsByPatientId(@Param("patientId") UUID patientId, @Param("currentDate") LocalDate currentDate);
    
    @Query("SELECT COUNT(p) FROM Prescription p WHERE p.patient.id = :patientId AND p.status = :status")
    Long countByPatientIdAndStatus(@Param("patientId") UUID patientId, @Param("status") PrescriptionStatus status);
    
    @Query("SELECT p FROM Prescription p WHERE p.patient.id = :patientId AND p.doctor.id = :doctorId ORDER BY p.createdAt DESC")
    List<Prescription> findByPatientIdAndDoctorId(@Param("patientId") UUID patientId, @Param("doctorId") UUID doctorId);
}

