<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.chinaweal.aiccs.org.mapper.OauthAccessTokenMapper">

    <!-- 通用查询映射结果 -->
    <resultMap id="BaseResultMap" type="com.chinaweal.aiccs.org.entity.OauthAccessToken">
        <id column="token_id" property="tokenId"/>
        <result column="access_token" property="accessToken"/>
        <result column="refresh_token" property="refreshToken"/>
        <result column="client_id" property="clientId"/>
        <result column="user_id" property="userId"/>
        <result column="user_name" property="userName"/>
        <result column="scope" property="scope"/>
        <result column="grant_type" property="grantType"/>
        <result column="expires_in" property="expiresIn"/>
        <result column="refresh_expires_in" property="refreshExpiresIn"/>
        <result column="is_active" property="isActive"/>
        <result column="create_time" property="createTime"/>
        <result column="update_time" property="updateTime"/>
    </resultMap>

    <!-- 通用查询结果列 -->
    <sql id="Base_Column_List">
        token_id, access_token, refresh_token, client_id, user_id, user_name, scope,
        grant_type, expires_in, refresh_expires_in, is_active, create_time, update_time
    </sql>

    <!-- 根据访问令牌查询信息 -->
    <select id="selectByAccessToken" resultMap="BaseResultMap">
        SELECT
        <include refid="Base_Column_List"/>
        FROM oauth_access_token
        WHERE access_token = #{accessToken}
        LIMIT 1
    </select>

    <!-- 根据刷新令牌查询信息 -->
    <select id="selectByRefreshToken" resultMap="BaseResultMap">
        SELECT
        <include refid="Base_Column_List"/>
        FROM oauth_access_token
        WHERE refresh_token = #{refreshToken}
        LIMIT 1
    </select>

    <!-- 根据刷新令牌和客户端ID查询信息 -->
    <select id="selectByRefreshTokenAndClientId" resultMap="BaseResultMap">
        SELECT
        <include refid="Base_Column_List"/>
        FROM oauth_access_token
        WHERE refresh_token = #{refreshToken}
        AND client_id = #{clientId}
        LIMIT 1
    </select>

    <!-- 根据用户ID和客户端ID查询有效的访问令牌 -->
    <select id="selectActiveByUserIdAndClientId" resultMap="BaseResultMap">
        SELECT
        <include refid="Base_Column_List"/>
        FROM oauth_access_token
        WHERE user_id = #{userId}
        AND client_id = #{clientId}
        AND is_active = '1'
        AND expires_in > NOW()
        ORDER BY create_time DESC
        LIMIT 1
    </select>

</mapper>