package com.mvrent.carrental.repository;

import com.mvrent.carrental.model.Car;
import com.mvrent.carrental.model.CarStatus;
import com.mvrent.carrental.model.CarType;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.query.Param;

import java.time.LocalDate;
import java.util.List;

public interface CarRepository extends JpaRepository<Car, Long> {

    List<Car> findByAvailableTrueAndStatus(CarStatus status);

    List<Car> findByType(CarType type);

    List<Car> findByVendorIdOrderByMake(Long vendorId);

    long countByVendorId(Long vendorId);

    @Query("""
            SELECT c FROM Car c
            WHERE c.available = true
              AND c.status = com.mvrent.carrental.model.CarStatus.ACTIVE
              AND c.id NOT IN (
                  SELECT b.car.id FROM Booking b
                  WHERE b.status IN (com.mvrent.carrental.model.BookingStatus.PENDING,
                                     com.mvrent.carrental.model.BookingStatus.CONFIRMED)
                    AND b.pickupDate <= :returnDate
                    AND b.returnDate >= :pickupDate
              )
            """)
    List<Car> findAvailableBetween(@Param("pickupDate") LocalDate pickupDate,
                                   @Param("returnDate") LocalDate returnDate);
}
