package com.mvrent.carrental.service;

import com.mvrent.carrental.model.*;
import com.mvrent.carrental.repository.MaintenanceRepository;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

@Service
@RequiredArgsConstructor
public class MaintenanceService {

    private static final List<MaintenanceStatus> OPEN =
            List.of(MaintenanceStatus.SCHEDULED, MaintenanceStatus.IN_PROGRESS);

    private final MaintenanceRepository maintenanceRepository;
    private final CarService carService;

    public List<MaintenanceRecord> findAll() {
        return maintenanceRepository.findAllByOrderByServiceDateDescIdDesc();
    }

    public List<MaintenanceRecord> findByCar(Long carId) {
        return maintenanceRepository.findByCarIdOrderByServiceDateDescIdDesc(carId);
    }

    public MaintenanceRecord findById(Long id) {
        return maintenanceRepository.findById(id)
                .orElseThrow(() -> new IllegalArgumentException("Maintenance record not found: " + id));
    }

    @Transactional
    public MaintenanceRecord save(MaintenanceRecord record, Long carId) {
        Car car = carService.findById(carId);
        record.setCar(car);
        MaintenanceRecord saved = maintenanceRepository.save(record);
        syncCarStatus(car);
        return saved;
    }

    @Transactional
    public void delete(Long id) {
        MaintenanceRecord r = findById(id);
        Car car = r.getCar();
        maintenanceRepository.delete(r);
        if (car != null) syncCarStatus(car);
    }

    /**
     * A car with any open (scheduled / in-progress) job is forced to MAINTENANCE;
     * once all jobs are closed it returns to ACTIVE (unless RETIRED).
     */
    private void syncCarStatus(Car car) {
        if (car.getStatus() == CarStatus.RETIRED) return;
        boolean hasOpen = maintenanceRepository.existsByCarIdAndStatusIn(car.getId(), OPEN);
        CarStatus target = hasOpen ? CarStatus.MAINTENANCE : CarStatus.ACTIVE;
        if (car.getStatus() != target) {
            car.setStatus(target);
            carService.save(car);
        }
    }
}
