package com.ttstd.signaling.store;

import com.ttstd.signaling.model.LoginSession;
import com.ttstd.signaling.model.PrincipalType;
import com.ttstd.signaling.repository.LoginSessionRepository;
import org.springframework.context.annotation.Profile;
import org.springframework.stereotype.Component;

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

/** JPA 实现：登录会话持久化到 MySQL。仅在 storage.mode=jpa（默认）时生效。 */
@Component
@Profile("!memory")
public class JpaSessionStore implements SessionStore {

    private final LoginSessionRepository repository;

    public JpaSessionStore(LoginSessionRepository repository) {
        this.repository = repository;
    }

    @Override
    public LoginSession save(LoginSession session) {
        return repository.save(session);
    }

    @Override
    public Optional<LoginSession> findBySessionId(String sessionId) {
        return repository.findById(sessionId);
    }

    @Override
    public List<LoginSession> listByPrincipal(String principalId) {
        return repository.findByPrincipalId(principalId);
    }

    @Override
    public List<LoginSession> listByPrincipalAndType(String principalId, PrincipalType type) {
        return repository.findByPrincipalIdAndPrincipalType(principalId, type);
    }

    @Override
    public List<LoginSession> listAll() {
        return repository.findAll();
    }

    @Override
    public void delete(String sessionId) {
        repository.deleteBySessionId(sessionId);
    }

    @Override
    public void deleteByPrincipal(String principalId) {
        repository.findByPrincipalId(principalId).forEach(s -> repository.delete(s));
    }

    @Override
    public int revokeByPrincipal(String principalId) {
        return repository.revokeByPrincipalId(principalId);
    }

    @Override
    public int revokeBySessionId(String sessionId) {
        return repository.revokeBySessionId(sessionId);
    }

    @Override
    public long countByPrincipalAndType(String principalId, PrincipalType type) {
        return repository.countByPrincipalIdAndPrincipalType(principalId, type);
    }
}
