package api

import (
	"errors"
	"net/http"
)

func (api *Api) RegisterDeviceToken(w http.ResponseWriter, r *http.Request) {
	user := GetUser(r)

	var input struct {
		Token string `json:"token"`
	}
	if err := api.readJSON(w, r, &input); err != nil {
		api.BadRequestResponse(w, r, err)
		return
	}
	if input.Token == "" {
		api.BadRequestResponse(w, r, errors.New("token must be provided"))
		return
	}

	if err := api.App.Models.DeviceTokens.Insert(user.ID, input.Token); err != nil {
		api.ServerErrorResponse(w, r, err)
		return
	}

	w.WriteHeader(http.StatusNoContent)
}

func (api *Api) DeleteDeviceToken(w http.ResponseWriter, r *http.Request) {
	user := GetUser(r)

	var input struct {
		Token string `json:"token"`
	}
	if err := api.readJSON(w, r, &input); err != nil {
		api.BadRequestResponse(w, r, err)
		return
	}
	if input.Token == "" {
		api.BadRequestResponse(w, r, errors.New("token must be provided"))
		return
	}

	tokens, err := api.App.Models.DeviceTokens.GetForUser(user.ID)
	if err != nil {
		api.ServerErrorResponse(w, r, err)
		return
	}
	owns := false
	for _, dt := range tokens {
		if dt.Token == input.Token {
			owns = true
			break
		}
	}
	if !owns {
		api.NotFoundResponse(w, r)
		return
	}

	if err := api.App.Models.DeviceTokens.Delete(input.Token); err != nil {
		api.ServerErrorResponse(w, r, err)
		return
	}

	w.WriteHeader(http.StatusNoContent)
}
