<?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.erp.ai.mapper.AiAgentApiKeyMapper">

  <resultMap id="ApiKeyMap" type="com.erp.ai.model.AiAgentApiKey">
    <id property="id" column="id"/>
    <result property="name" column="name"/>
    <result property="key_hash" column="key_hash"/>
    <result property="key_prefix" column="key_prefix"/>
    <result property="user_id" column="user_id"/>
    <result property="company_code" column="company_code"/>
    <result property="agent_id" column="agent_id"/>
    <result property="permissions" column="permissions"/>
    <result property="rate_limit" column="rate_limit"/>
    <result property="monthly_token_limit" column="monthly_token_limit"/>
    <result property="status" column="status"/>
    <result property="last_used_at" column="last_used_at"/>
    <result property="usage_count" column="usage_count"/>
    <result property="total_tokens" column="total_tokens"/>
    <result property="expires_at" column="expires_at"/>
    <result property="created_at" column="created_at"/>
  </resultMap>

  <sql id="ApiKeyColumns">
    id, name, key_hash, key_prefix, user_id, company_code, agent_id,
    permissions::text AS permissions, rate_limit, monthly_token_limit,
    status, last_used_at, usage_count, total_tokens, expires_at, created_at
  </sql>

  <select id="listAll" resultMap="ApiKeyMap">
    SELECT <include refid="ApiKeyColumns"/>
    FROM ai_agent_api_keys ORDER BY created_at DESC
  </select>

  <select id="listByUser" resultMap="ApiKeyMap">
    SELECT <include refid="ApiKeyColumns"/>
    FROM ai_agent_api_keys WHERE user_id = #{userId} ORDER BY created_at DESC
  </select>

  <select id="getById" resultMap="ApiKeyMap">
    SELECT <include refid="ApiKeyColumns"/>
    FROM ai_agent_api_keys WHERE id = #{id}
  </select>

  <select id="getByKeyHash" resultMap="ApiKeyMap">
    SELECT <include refid="ApiKeyColumns"/>
    FROM ai_agent_api_keys
    WHERE key_hash = #{keyHash} AND status = 'active'
  </select>

  <insert id="insert" parameterType="com.erp.ai.model.AiAgentApiKey" useGeneratedKeys="true" keyProperty="id">
    INSERT INTO ai_agent_api_keys
      (name, key_hash, key_prefix, user_id, company_code, agent_id, permissions, rate_limit, monthly_token_limit, expires_at)
    VALUES (#{name}, #{key_hash}, #{key_prefix}, #{user_id}, #{company_code}, #{agent_id},
            COALESCE(#{permissions}::jsonb, '["chat"]'::jsonb),
            COALESCE(#{rate_limit}, 60),
            COALESCE(#{monthly_token_limit}, 1000000),
            #{expires_at})
  </insert>

  <delete id="delete">
    DELETE FROM ai_agent_api_keys
    WHERE id = #{id} AND (user_id = #{userId} OR #{userId} = 'wace')
  </delete>

  <update id="updateLastUsed">
    UPDATE ai_agent_api_keys
    SET last_used_at = NOW(), usage_count = usage_count + 1
    WHERE id = #{id}
  </update>

  <update id="addTokenUsage">
    UPDATE ai_agent_api_keys
    SET total_tokens = total_tokens + #{tokens}
    WHERE id = #{id}
  </update>

  <select id="countActive" resultType="int">
    SELECT COUNT(*) FROM ai_agent_api_keys WHERE status = 'active'
  </select>

</mapper>
