package com.dora.mapper;

import com.dora.entity.ApiKey;
import org.apache.ibatis.annotations.Mapper;
import org.apache.ibatis.annotations.Param;
import org.apache.ibatis.annotations.Select;
import org.apache.ibatis.annotations.Insert;
import org.apache.ibatis.annotations.Update;
import org.apache.ibatis.annotations.Delete;

import java.util.List;

/**
 * API密钥Mapper接口
 */
@Mapper
public interface ApiKeyMapper {

    /**
     * 根据用户ID查询API密钥（只查询未删除的）
     */
    @Select("SELECT * FROM api_key WHERE user_id = #{userId} AND is_deleted = 0")
    ApiKey selectByUserId(@Param("userId") Long userId);

    /**
     * 根据用户ID查询API密钥（包括已删除的）
     */
    @Select("SELECT * FROM api_key WHERE user_id = #{userId}")
    ApiKey selectByUserIdIncludeDeleted(@Param("userId") Long userId);

    /**
     * 根据密钥值查询API密钥
     */
    @Select("SELECT * FROM api_key WHERE key_value = #{keyValue} AND is_deleted = 0")
    ApiKey selectByKeyValue(@Param("keyValue") String keyValue);

    /**
     * 插入API密钥
     */
    @Insert("INSERT INTO api_key (user_id, key_value, is_active, create_time, update_time, is_deleted) " +
            "VALUES (#{userId}, #{keyValue}, #{isActive}, NOW(), NOW(), 0)")
    int insert(ApiKey apiKey);

    /**
     * 更新API密钥
     */
    @Update("UPDATE api_key SET key_value = #{keyValue}, is_active = #{isActive}, " +
            "last_used_at = #{lastUsedAt}, update_time = NOW(), is_deleted = #{isDeleted} WHERE id = #{id}")
    int update(ApiKey apiKey);

    /**
     * 逻辑删除API密钥
     */
    @Update("UPDATE api_key SET is_deleted = 1, update_time = NOW() WHERE id = #{id}")
    int deleteById(@Param("id") Long id);

    /**
     * 根据用户ID删除API密钥
     */
    @Update("UPDATE api_key SET is_deleted = 1, update_time = NOW() WHERE user_id = #{userId}")
    int deleteByUserId(@Param("userId") Long userId);
} 