package com.mvrent.carrental.service;

import com.mvrent.carrental.model.InspectionRecord;
import com.mvrent.carrental.repository.BookingRepository;
import com.mvrent.carrental.repository.InspectionRepository;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

@Service
@RequiredArgsConstructor
public class InspectionService {

    private final InspectionRepository inspectionRepository;
    private final CarService carService;
    private final BookingRepository bookingRepository;

    public List<InspectionRecord> findAll() {
        return inspectionRepository.findAllByOrderByInspectionDateDescIdDesc();
    }

    public List<InspectionRecord> findByCar(Long carId) {
        return inspectionRepository.findByCarIdOrderByInspectionDateDescIdDesc(carId);
    }

    public InspectionRecord findById(Long id) {
        return inspectionRepository.findById(id)
                .orElseThrow(() -> new IllegalArgumentException("Inspection not found: " + id));
    }

    @Transactional
    public InspectionRecord save(InspectionRecord record, Long carId, Long bookingId) {
        record.setCar(carService.findById(carId));
        record.setBooking(bookingId != null ? bookingRepository.findById(bookingId).orElse(null) : null);
        return inspectionRepository.save(record);
    }

    @Transactional
    public void delete(Long id) {
        inspectionRepository.deleteById(id);
    }
}
