package com.lingyue.auth.repository;

import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.lingyue.auth.entity.Session;
import org.apache.ibatis.annotations.Mapper;
import org.apache.ibatis.annotations.Param;
import org.apache.ibatis.annotations.Select;
import org.apache.ibatis.annotations.Delete;

import java.util.Date;
import java.util.List;

/**
 * 会话Repository
 */
@Mapper
public interface SessionRepository extends BaseMapper<Session> {
    
    /**
     * 根据Token哈希查找会话
     */
    @Select("SELECT * FROM sessions WHERE token_hash = #{tokenHash}")
    Session findByTokenHash(@Param("tokenHash") String tokenHash);
    
    /**
     * 根据刷新Token哈希查找会话
     */
    @Select("SELECT * FROM sessions WHERE refresh_token_hash = #{refreshTokenHash}")
    Session findByRefreshTokenHash(@Param("refreshTokenHash") String refreshTokenHash);
    
    /**
     * 根据用户ID查找所有会话
     */
    @Select("SELECT * FROM sessions WHERE user_id = #{userId}")
    List<Session> findByUserId(@Param("userId") String userId);
    
    /**
     * 删除过期的会话
     */
    @Delete("DELETE FROM sessions WHERE expires_at < #{now}")
    void deleteExpiredSessions(@Param("now") Date now);
    
    /**
     * 删除用户的所有会话
     */
    @Delete("DELETE FROM sessions WHERE user_id = #{userId}")
    void deleteByUserId(@Param("userId") String userId);
}
