package api

import (
	"errors"
	"net/http"

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

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 := api.readJSON(w, r, &input); err != nil {
		api.BadRequestResponse(w, r, err)
		return
	}

	if err := api.App.CastVote(input.IssueID, input.OptionID, input.Nonce, input.Signature); err != nil {
		switch {
		case errors.Is(err, data.ErrRecordNotFound):
			api.NotFoundResponse(w, r)
		case errors.Is(err, data.ErrInvalidSignature):
			api.InvalidSignatureResponse(w, r)
		case errors.Is(err, data.ErrDuplicateVote):
			api.AlreadyVotedResponse(w, r)
		default:
			api.ServerErrorResponse(w, r, err)
		}
		return
	}

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