package main

import (
	"strconv"
	"strings"

	restful "github.com/emicklei/go-restful"
	"novit.tech/direktil/local-server/secretstore"
)

type AddKeyReq struct {
	NamedPassphrase `json:",inline"`
	Hash            []byte `json:",omitempty"`
}

func wsStoreAddKey(req *restful.Request, resp *restful.Response) {
	np := AddKeyReq{}

	err := req.ReadEntity(&np)
	if err != nil {
		wsBadRequest(resp, err.Error())
		return
	}

	np.Name = strings.TrimSpace(np.Name)

	if len(np.Name) == 0 {
		wsBadRequest(resp, "no name given")
		return
	}

	if len(np.Hash) == 0 && len(np.Passphrase) == 0 {
		wsBadRequest(resp, "no hash or passphrase given")
		return
	}

	if len(np.Hash) != 0 && len(np.Hash) != 32 {
		wsBadRequest(resp, "hash of a wrong length")
		return
	}

	for _, k := range secStore.Keys {
		if k.Name == np.Name {
			wsBadRequest(resp, "there's already a passphrase named "+strconv.Quote(np.Name))
			return
		}
	}

	if len(np.Hash) != 0 {
		hash := [32]byte{}
		copy(hash[:], np.Hash[:32])
		secStore.AddRawKey(np.Name, hash)
	} else {
		secStore.AddKey(np.Name, np.Passphrase)
	}

	defer updateState()

	err = secStore.SaveTo(secKeysStorePath())
	if err != nil {
		wsError(resp, err)
		return
	}
}

func wsStoreDelKey(req *restful.Request, resp *restful.Response) {
	name := ""

	err := req.ReadEntity(&name)
	if err != nil {
		wsBadRequest(resp, err.Error())
		return
	}

	newKeys := make([]secretstore.KeyEntry, 0, len(secStore.Keys))
	for _, k := range secStore.Keys {
		if k.Name == name {
			continue
		}

		newKeys = append(newKeys, k)
	}

	if len(newKeys) == 0 {
		wsBadRequest(resp, "can't remove the last key from the store")
		return
	}

	secStore.Keys = newKeys
	defer updateState()

	err = secStore.SaveTo(secKeysStorePath())
	if err != nil {
		wsError(resp, err)
		return
	}
}
