-module(db@published).
-compile([no_auto_import, nowarn_unused_vars, nowarn_unused_function, nowarn_nomatch]).

-export([add/2]).
-export_type([get_err/0]).

-type get_err() :: {get_db_err, binary()}.

-spec published_decoder() -> fun((gleam@dynamic:dynamic_()) -> {ok, integer()} |
    {error, list(gleam@dynamic:decode_error())}).
published_decoder() ->
    gleam@dynamic:decode1(
        fun(Num_args) -> Num_args end,
        gleam@dynamic:field(<<"template_id"/utf8>>, fun gleam@dynamic:int/1)
    ).

-spec insert(sqlight:connection(), integer()) -> {ok, nil} |
    {error, sqlight:error()}.
insert(Conn, Num_args) ->
    Row = [cake@insert:int(Num_args)],
    Fields = [<<"numArgs"/utf8>>],
    Query = begin
        _pipe@1 = cake@insert:from_values(
            <<"published"/utf8>>,
            Fields,
            [begin
                    _pipe = Row,
                    cake@insert:row(_pipe)
                end]
        ),
        cake@insert:to_query(_pipe@1)
    end,
    _pipe@2 = Conn,
    db@db:insert(_pipe@2, Query, published_decoder()).

-spec add(sqlight:connection(), integer()) -> {ok, integer()} |
    {error, db@template:add_err()}.
add(Conn, Num_args) ->
    gleam@result:'try'(
        begin
            _pipe = Conn,
            _pipe@1 = insert(_pipe, Num_args),
            gleam@result:map_error(
                _pipe@1,
                fun(E) -> {add_db_err, erlang:element(3, E)} end
            )
        end,
        fun(_use0) ->
            nil = _use0,
            _pipe@2 = Conn,
            _pipe@3 = db@db:select_last_id(_pipe@2, <<"published"/utf8>>),
            gleam@result:map_error(
                _pipe@3,
                fun(_) ->
                    {add_db_err, <<"new published id-select failed"/utf8>>}
                end
            )
        end
    ).
