package api

import (
	"net/http"

	"party.at/party/internal/data"
	"party.at/party/cmd/party/common"
)

func (api *Api) Vote(w http.ResponseWriter, r *http.Request) {
	var input struct {
		IssueID   int64  `json:"issue_id"`
		OptionID  int64  `json:"option_id"`
		Nonce     []byte `json:"nonce"`
		Signature []byte `json:"signature"`
	}

	if err := common.ReadJSON(w, r, &input); err != nil {
		api.errorResponse(w, r, data.ErrBadRequest)
		return
	}

	if err := api.App.CastVote(input.IssueID, input.OptionID, input.Nonce, input.Signature); err != nil {
		api.ServerErrorResponse(w, r, err)

		return
	}

	if err := common.WriteJSON(w, http.StatusCreated, common.Envelope{"message": "vote successfully cast"}, nil); err != nil {
		api.ServerErrorResponse(w, r, err)
	}
}
