%%%-------------------------------------------------------------------
%%% @author anlicheng
%%% @copyright (C) 2025, <COMPANY>
%%% @doc
%%%
%%% @end
%%% Created : 14. 11月 2025 23:29
%%%-------------------------------------------------------------------
-module(endpoint_kafka_test).
-author("anlicheng").
-include_lib("endpoint/include/endpoint.hrl").

%% API
-export([start_manual/0, test_consumer/0]).

start_manual() ->
    Name = endpoint:get_name(100),
    {ok, Pid} = endpoint_kafka:start_link(Name, #endpoint{
        id = 100,
        %% 全局唯一，在路由规则中通过名称来指定
        matcher = <<"/dhlr/device/*/*">>,
        %% 标题描述
        title = <<"test_kafka_title">>,
        %% 配置项, 格式: #{<<"protocol">> => <<"http|https|ws|kafka|mqtt">>, <<"args">> => #{}}
        config = #kafka_endpoint{
            sasl_config = {plain, <<"test">>, <<"test123">>},
            bootstrap_servers = [{"118.178.229.213", 9092}],
            topic = <<"dhlr_data">>
        }
    }),

    Json = iolist_to_binary(json:encode(#{
        <<"name">> => <<"anlicheng">>,
        <<"age">> => 30
    })),

    endpoint:forward(Pid, Json),
    ok.

test_consumer() ->
    KafkaBootstrapEndpoints = [{"118.178.229.213", 9092}],
    Topic = <<"dhlr_data">>,

    ClientConfig = [
        {sasl, {plain, <<"test">>, <<"test123">>}},
        {reconnect_cool_down_seconds, 5},
        {socket_options, [{keepalive, true}]}
    ],

    ok = brod:start_client(KafkaBootstrapEndpoints, client1, ClientConfig),
    SubscriberCallbackFun = fun(_Partition, Msg, ShellPid = CallbackState) ->
        logger:debug("call here msg: ~p", [Msg]),
        ShellPid ! Msg, {ok, ack, CallbackState}
                            end,
    Res = brod_topic_subscriber:start_link(client1, Topic, all,
        _ConsumerConfig=[{begin_offset, 0}],
        _CommittedOffsets=[], message, SubscriberCallbackFun,
        _CallbackState=self()),

    logger:debug("start subscriber res: ~p", [Res]).
