package com.zioinfo.kintex.ai;

import com.zioinfo.kintex.tenant.TenantContext;
import org.apache.ibatis.annotations.Insert;
import org.apache.ibatis.annotations.Mapper;
import org.apache.ibatis.annotations.Param;
import org.apache.ibatis.annotations.Select;

import java.util.List;
import java.util.Map;

/**
 * F100 AI 설정({@code ai_config} key/value) 매퍼 — 테넌트 스코프(★표준: PK = (tenant_id, config_key)).
 * <p>★ 보안 불변: 이 테이블에는 <b>API 키를 저장하지 않는다</b>(키는 env 전용). provider/모델/활성화 플래그만 보관.
 */
@Mapper
public interface AiConfigMapper {

    /** 전체 설정 행(config_key, config_val) — 현재 테넌트. */
    @Select("SELECT config_key AS \"key\", config_val AS \"val\" FROM ai_config WHERE tenant_id = #{tenantId}")
    List<Map<String, Object>> findAllByTenant(@Param("tenantId") String tenantId);

    default List<Map<String, Object>> findAll() {
        return findAllByTenant(TenantContext.currentTenantId());
    }

    /** 단일 값(미설정 시 null) — 현재 테넌트. */
    @Select("SELECT config_val FROM ai_config WHERE tenant_id = #{tenantId} AND config_key = #{key}")
    String findValByTenant(@Param("tenantId") String tenantId, @Param("key") String key);

    default String findVal(String key) {
        return findValByTenant(TenantContext.currentTenantId(), key);
    }

    /** 멱등 upsert — (tenant_id, config_key) 충돌 시 값·수정자·수정시각 갱신. */
    @Insert("""
            INSERT INTO ai_config (tenant_id, config_key, config_val, updated_by, updated_at)
            VALUES (#{tenantId}, #{key}, #{val}, #{actor}, now())
            ON CONFLICT (tenant_id, config_key) DO UPDATE
               SET config_val = EXCLUDED.config_val,
                   updated_by = EXCLUDED.updated_by,
                   updated_at = now()
            """)
    int upsertByTenant(@Param("tenantId") String tenantId, @Param("key") String key,
                       @Param("val") String val, @Param("actor") String actor);

    default int upsert(String key, String val, String actor) {
        return upsertByTenant(TenantContext.currentTenantId(), key, val, actor);
    }
}
