%%%-------------------------------------------------------------------
%%% @author anlicheng
%%% @copyright (C) 2024, <COMPANY>
%%% @doc
%%%
%%% @end
%%% Created : 07. 5月 2024 11:17
%%%-------------------------------------------------------------------
-module(endpoint_http).
-author("anlicheng").
-include("endpoint.hrl").

-behaviour(gen_server).

%% API
-export([start_link/2]).

%% gen_server callbacks
-export([init/1, handle_call/3, handle_cast/2, handle_info/2, terminate/2, code_change/3]).

-define(SERVER, ?MODULE).

-record(state, {
    endpoint :: #endpoint{},
    buffer :: endpoint_buffer:buffer()
}).

%%%===================================================================
%%% API
%%%===================================================================

%% @doc Spawns the server and registers the local name (unique)
-spec(start_link(LocalName :: term(), Endpoint :: #endpoint{}) ->
    {ok, Pid :: pid()} | ignore | {error, Reason :: term()}).
start_link(LocalName, Endpoint = #endpoint{config = #http_endpoint{}}) ->
    gen_server:start_link({via, gproc, {n, l, LocalName}}, ?MODULE, [Endpoint], []).

%%%===================================================================
%%% gen_server callbacks
%%%===================================================================

%% @private
%% @doc Initializes the server
-spec(init(Args :: term()) ->
    {ok, State :: #state{}} | {ok, State :: #state{}, timeout() | hibernate} |
    {stop, Reason :: term()} | ignore).
init([Endpoint = #endpoint{matcher = Matcher, config = #http_endpoint{pool_size = PoolSize}}]) ->
    ok = endpoint_util:set_metadata(),
    endpoint_subscription:subscribe(Matcher, self()),
    Buffer = endpoint_buffer:new(Endpoint, PoolSize),
    {ok, #state{endpoint = Endpoint, buffer = Buffer}}.

%% @private
%% @doc Handling call messages
-spec(handle_call(Request :: term(), From :: {pid(), Tag :: term()},
    State :: #state{}) ->
    {reply, Reply :: term(), NewState :: #state{}} |
    {reply, Reply :: term(), NewState :: #state{}, timeout() | hibernate} |
    {noreply, NewState :: #state{}} |
    {noreply, NewState :: #state{}, timeout() | hibernate} |
    {stop, Reason :: term(), Reply :: term(), NewState :: #state{}} |
    {stop, Reason :: term(), NewState :: #state{}}).
handle_call(get_stat, _From, State = #state{buffer = Buffer}) ->
    Stat = endpoint_buffer:stat(Buffer),
    {reply, {ok, Stat}, State}.

%% @private
%% @doc Handling cast messages
-spec(handle_cast(Request :: term(), State :: #state{}) ->
    {noreply, NewState :: #state{}} |
    {noreply, NewState :: #state{}, timeout() | hibernate} |
    {stop, Reason :: term(), NewState :: #state{}}).
handle_cast({forward, Metric}, State = #state{buffer = Buffer}) ->
    NBuffer = endpoint_buffer:append(Metric, Buffer),
    {noreply, State#state{buffer = NBuffer}};
handle_cast({reload, NEndpoint = #endpoint{matcher = NMatcher, config = #http_endpoint{pool_size = PoolSize}}}, State = #state{endpoint = #endpoint{matcher = Matcher}, buffer = Buffer}) ->
    ensure_subscription(Matcher, NMatcher),
    NBuffer = endpoint_buffer:resize(Buffer, PoolSize),
    {noreply, State#state{endpoint = NEndpoint, buffer = NBuffer}};

handle_cast(cleanup, State = #state{buffer = Buffer}) ->
    NBuffer = endpoint_buffer:cleanup(Buffer),
    {noreply, State#state{buffer = NBuffer}}.

%% @private
%% @doc Handling all non call/cast messages
-spec(handle_info(Info :: timeout() | term(), State :: #state{}) ->
    {noreply, NewState :: #state{}} |
    {noreply, NewState :: #state{}, timeout() | hibernate} |
    {stop, Reason :: term(), NewState :: #state{}}).
handle_info({next_data, Id, Metric}, State = #state{buffer = Buffer, endpoint = #endpoint{config = #http_endpoint{url = Url, token = Token}}}) ->
    Headers = [{<<"Content-Type">>, <<"application/json">>}] ++ patch_headers(Metric, Token),
    case hackney:request(post, Url, Headers, Metric) of
        {ok, HttpCode, _, ClientRef} when HttpCode >= 200, HttpCode < 300 ->
            RespBody = read_response_body(ClientRef),
            logger:debug("[endpoint_http] url: ~p, response is: ~p", [Url, RespBody]),
            NBuffer = endpoint_buffer:ack(Id, Buffer),
            {noreply, State#state{buffer = NBuffer}};
        {ok, HttpCode, _, ClientRef} ->
            RespBody = read_response_body(ClientRef),
            logger:warning("[endpoint_http] url: ~p, http_code: ~p, response is: ~p", [Url, HttpCode, RespBody]),
            {noreply, State};
        {error, Reason} ->
            logger:warning("[endpoint_http] url: ~p, get error: ~p", [Url, Reason]),
            {noreply, State}
    end;
handle_info({timeout, TimerRef, {endpoint_buffer_retry, Id, Payload}}, State = #state{buffer = Buffer}) ->
    NBuffer = endpoint_buffer:handle_timeout(TimerRef, Id, Payload, Buffer),
    {noreply, State#state{buffer = NBuffer}}.

%% @private
%% @doc This function is called by a gen_server when it is about to
%% terminate. It should be the opposite of Module:init/1 and do any
%% necessary cleaning up. When it returns, the gen_server terminates
%% with Reason. The return value is ignored.
-spec(terminate(Reason :: (normal | shutdown | {shutdown, term()} | term()),
    State :: #state{}) -> term()).
terminate(_Reason, #state{buffer = Buffer}) ->
    _ = endpoint_buffer:cleanup(Buffer),
    ok.

%% @private
%% @doc Convert process state when code is changed
-spec(code_change(OldVsn :: term() | {down, term()}, State :: #state{},
    Extra :: term()) ->
    {ok, NewState :: #state{}} | {error, Reason :: term()}).
code_change(_OldVsn, State = #state{}, _Extra) ->
    {ok, State}.

%%%===================================================================
%%% Internal functions
%%%===================================================================

-spec ensure_subscription(binary(), binary()) -> ok.
ensure_subscription(Matcher, Matcher) ->
    ok;
ensure_subscription(Matcher, NMatcher) ->
    ok = endpoint_subscription:unsubscribe(Matcher, self()),
    endpoint_subscription:subscribe(NMatcher, self()).

-spec read_response_body(reference()) -> binary() | term().
read_response_body(ClientRef) ->
    case hackney:body(ClientRef) of
        {ok, RespBody} ->
            hackney:close(ClientRef),
            RespBody;
        {error, Reason} ->
            hackney:close(ClientRef),
            Reason
    end.

-spec patch_headers(Metric :: binary(), any()) -> list().
patch_headers(Metric, Token) when is_binary(Token), Token /= <<>> ->
    Sign = endpoint_util:sha256(erlang:iolist_to_binary([Token, Metric, Token])),
    [{<<"X-Signature">>, Sign}];
patch_headers(_, _) ->
    [].
