
// myCipherKeys provides functions to save a user's received message cipher keys
// The user stores these in case they want to report a message
// They share the message's cipher key in their report, enabling moderators to decrypt and review the message

package myCipherKeys

//TODO: Add a function to prune old cipher keys for deleted and expired messages

import "seekia/internal/encoding"
import "seekia/internal/myDatastores/myMap"
import "seekia/internal/messaging/readMessages"

import "errors"

var messageCipherKeysMapDatastore *myMap.MyMap

// This function must be called whenever an app user signs in
func InitializeMyMessageCipherKeysDatastore()error{

	newMessagesCipherKeysMapDatastore, err := myMap.CreateNewMap("MyMessageCipherKeys")
	if (err != nil) { return err }

	messageCipherKeysMapDatastore = newMessagesCipherKeysMapDatastore

	return nil
}

func SaveMessageCipherKey(messageHash [26]byte, messageCipherKey [32]byte)error{

	messageHashString := encoding.EncodeBytesToHexString(messageHash[:])
	messageCipherKeyString := encoding.EncodeBytesToHexString(messageCipherKey[:])

	err := messageCipherKeysMapDatastore.SetMapEntry(messageHashString, messageCipherKeyString)
	if (err != nil) { return err }

	return nil
}


//Outputs:
//	-bool: Message Cipher key found
//	-[32]byte: Message cipher key
//	-error
func GetMessageCipherKey(messageHash [26]byte)(bool, [32]byte, error){

	messageHashHex := encoding.EncodeBytesToHexString(messageHash[:])

	exists, messageCipherKeyHex, err := messageCipherKeysMapDatastore.GetMapEntry(messageHashHex)
	if (err != nil) { return false, [32]byte{}, err }
	if (exists == false) {
		return false, [32]byte{}, nil
	}

	messageCipherKey, err := readMessages.ReadMessageCipherKeyHex(messageCipherKeyHex)
	if (err != nil){
		return false, [32]byte{}, errors.New("messageCipherKeysMapDatastore contains invalid messageCipherKey: " + err.Error())
	}

	return true, messageCipherKey, nil
}



