package llc.arma.fleet.monitor.domain.service

import llc.arma.fleet.monitor.data.entity.BeaconEntity
import llc.arma.fleet.monitor.data.entity.BeaconStatus
import llc.arma.fleet.monitor.data.entity.DepartmentEntity
import llc.arma.fleet.monitor.data.entity.MachineTypeEntity
import llc.arma.fleet.monitor.data.repository.BeaconRepository
import llc.arma.fleet.monitor.data.repository.DepartmentRepository
import llc.arma.fleet.monitor.data.repository.MachineTypeRepository
import org.springframework.stereotype.Service

@Service
class ReferenceService(
    private val machineTypeRepository: MachineTypeRepository,
    private val departmentRepository: DepartmentRepository,
    private val beaconRepository: BeaconRepository,
) {
    fun getMachineTypes(): List<MachineTypeEntity> = machineTypeRepository.findAll()
    fun getDepartments(): List<DepartmentEntity> = departmentRepository.findAll()
    fun getBeacons(): List<BeaconEntity> = beaconRepository.findAll()
    fun getFreeBeacons(): List<BeaconEntity> = beaconRepository.findByStatus(BeaconStatus.FREE)

    fun createMachineType(name: String): MachineTypeEntity = machineTypeRepository.save(MachineTypeEntity(name = name))
    fun updateMachineType(id: Long, name: String): MachineTypeEntity {
        val type = machineTypeRepository.findById(id).orElseThrow { IllegalArgumentException("Тип машины не найден") }
        type.name = name
        return machineTypeRepository.save(type)
    }
    fun deleteMachineType(id: Long): Boolean {
        if (!machineTypeRepository.existsById(id)) return false
        machineTypeRepository.deleteById(id)
        return true
    }

    fun createDepartment(name: String): DepartmentEntity = departmentRepository.save(DepartmentEntity(name = name))
    fun updateDepartment(id: Long, name: String): DepartmentEntity {
        val department = departmentRepository.findById(id).orElseThrow { IllegalArgumentException("Подразделение не найдено") }
        department.name = name
        return departmentRepository.save(department)
    }
    fun deleteDepartment(id: Long): Boolean {
        if (!departmentRepository.existsById(id)) return false
        departmentRepository.deleteById(id)
        return true
    }
}
