package de.assecutor.votianlt.pages.service;

import de.assecutor.votianlt.model.AppDevice;
import de.assecutor.votianlt.repository.AppDeviceRepository;
import de.assecutor.votianlt.security.SecurityService;
import org.bson.types.ObjectId;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

@Service
@Transactional
public class AppDeviceService {

    private final AppDeviceRepository appDeviceRepository;
    private final SecurityService securityService;

    @Autowired
    public AppDeviceService(AppDeviceRepository appDeviceRepository, SecurityService securityService) {
        this.appDeviceRepository = appDeviceRepository;
        this.securityService = securityService;
    }

    public AppDevice createAppDevice(AppDevice appDevice) {
        // Set creation and update metadata
        appDevice.setErstelltAm(java.time.LocalDateTime.now());
        appDevice.setAktualisiertAm(java.time.LocalDateTime.now());

        // Set creator and updater - current user ID is required
        ObjectId currentUserId = securityService.getCurrentUserId();
        appDevice.setErstelltVon(currentUserId);
        appDevice.setAktualisiertVon(currentUserId);

        return appDeviceRepository.save(appDevice);
    }

    public List<AppDevice> findByCurrentUser() {
        ObjectId currentUserId = securityService.getCurrentUserId();
        return appDeviceRepository.findByErstelltVon(currentUserId);
    }

    public List<AppDevice> findUnassignedDevices() {
        return appDeviceRepository.findByAppUserIdIsNull();
    }

    public AppDevice findById(ObjectId id) {
        return appDeviceRepository.findById(id).orElse(null);
    }

    public AppDevice updateAppDevice(AppDevice appDevice) {
        appDevice.setAktualisiertAm(java.time.LocalDateTime.now());
        appDevice.setAktualisiertVon(securityService.getCurrentUserId());
        return appDeviceRepository.save(appDevice);
    }

    public void deleteById(ObjectId id) {
        appDeviceRepository.deleteById(id);
    }
}
