package api

import (
	"fmt"
	"net/http"

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

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

	api.App.Logger.PrintInfo("register device token: request", map[string]string{
		"user_id": fmt.Sprint(user.ID),
	})

	var input struct {
		Token string `json:"token"`
	}
	if err := common.ReadJSON(w, r, &input); err != nil {
		api.App.Logger.PrintInfo("register device token: bad request", map[string]string{
			"user_id": fmt.Sprint(user.ID),
			"error":   err.Error(),
		})
		api.errorResponse(w, r, data.ErrBadRequest)
		return
	}
	if input.Token == "" {
		api.App.Logger.PrintInfo("register device token: empty token", map[string]string{
			"user_id": fmt.Sprint(user.ID),
		})
		api.errorResponse(w, r, data.ErrNoToken)
		return
	}

	if err := api.App.Models.DeviceTokens.Insert(user.ID, input.Token); err != nil {
		api.App.Logger.PrintError(err, map[string]string{
			"user_id": fmt.Sprint(user.ID),
		})
		api.ServerErrorResponse(w, r, err)
		return
	}

	api.App.Logger.PrintInfo("register device token: ok", map[string]string{
		"user_id": fmt.Sprint(user.ID),
	})
	w.WriteHeader(http.StatusNoContent)
}

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

	var input struct {
		Token string `json:"token"`
	}
	if err := common.ReadJSON(w, r, &input); err != nil {
		api.errorResponse(w, r, data.ErrBadRequest)
		return
	}
	if input.Token == "" {
		api.errorResponse(w, r, data.ErrNoToken)
		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.errorResponse(w, r, data.ErrRecordNotFound)
		return
	}

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

	w.WriteHeader(http.StatusNoContent)
}
