-module(hash_handler).
-behavior(cowboy_rest).

-export([init/2]).
-export([allowed_methods/2]).
-export([content_types_accepted/2]).
-export([content_types_provided/2]).
-export([resource_exists/2]).
-export([from_json/2]).
-export([to_json/2]).

init(Req, State) ->
  {cowboy_rest, Req, State}.

allowed_methods(Req, State) ->
  {[<<"POST">>, <<"OPTIONS">>], Req, State}.

content_types_accepted(Req, State) ->
  {[
    {<<"application/json">>, from_json}
  ],
  Req, State}.

content_types_provided(Req, State) ->
  % Required everytime the client request contains an
  % "Accept" header. Even if the method is never GET
  % and this callback is never called.
  {[
    {<<"application/json">>, to_json}
  ], Req, State}.

resource_exists(Req, State) ->
  {false, Req, State}.

from_json(Req, State) ->
  Rounds = cowboy_req:binding(item_id, Req, 12),
  {ok, Body, Req1} = cowboy_req:read_body(Req),
  {ok, Salt} = bcrypt:gen_salt(Rounds),
  {ok, Hash} = bcrypt:hashpw(Body, Salt),
  Res = thoas:encode(#{<<"digest">> => list_to_binary(Hash)}),
  Req2 = cowboy_req:set_resp_body(Res, Req1),
  {true, Req2, State}.

to_json(Req, State) ->
  % Not used but required by content_types_provided/2
  {true, Req, State}.