package com.ttstd.signaling.store;

import com.ttstd.signaling.model.DeviceAccount;
import com.ttstd.signaling.model.DeviceAllowlist;
import com.ttstd.signaling.repository.DeviceAccountRepository;
import com.ttstd.signaling.repository.DeviceAllowlistRepository;
import org.springframework.context.annotation.Profile;
import org.springframework.stereotype.Component;

import java.util.List;
import java.util.Optional;

/** JPA 实现：设备身份与 SN 白名单持久化到 MySQL。仅在 storage.mode=jpa（默认）时生效。 */
@Component
@Profile("!memory")
public class JpaDeviceStore implements DeviceStore {

    private final DeviceAccountRepository deviceRepository;
    private final DeviceAllowlistRepository allowlistRepository;

    public JpaDeviceStore(DeviceAccountRepository deviceRepository,
                          DeviceAllowlistRepository allowlistRepository) {
        this.deviceRepository = deviceRepository;
        this.allowlistRepository = allowlistRepository;
    }

    @Override
    public Optional<DeviceAccount> findByDeviceUid(String deviceUid) {
        return deviceRepository.findById(deviceUid);
    }

    @Override
    public Optional<DeviceAccount> findBySn(String sn) {
        return deviceRepository.findBySn(sn);
    }

    @Override
    public boolean existsBySn(String sn) {
        return deviceRepository.existsBySn(sn);
    }

    @Override
    public DeviceAccount save(DeviceAccount account) {
        return deviceRepository.save(account);
    }

    @Override
    public List<DeviceAccount> listAll() {
        return deviceRepository.findAll();
    }

    @Override
    public void delete(String deviceUid) {
        deviceRepository.deleteById(deviceUid);
    }

    @Override
    public boolean isSnAllowed(String sn) {
        return allowlistRepository.existsBySn(sn);
    }

    @Override
    public void addAllowedSn(DeviceAllowlist entry) {
        allowlistRepository.save(entry);
    }

    @Override
    public List<DeviceAllowlist> listAllowed() {
        return allowlistRepository.findAll();
    }

    @Override
    public void removeAllowedSn(String sn) {
        allowlistRepository.deleteById(sn);
    }
}
