package service

import (
	"context"
	"key-manager/crypto"
	"key-manager/dao"
	"key-manager/hd"
	"key-manager/key"
)

func (km *KeyManager) CreateMnemonic(ctx context.Context, req *CreateMnemonicRequest) (*CreateMnemonicResponse, error) {
	km.lk.Lock()
	defer km.lk.Unlock()

	mType := hd.MnemonicType(req.MnemonicType)
	if hd.Mnemonic12 != mType && hd.Mnemonic24 != mType {
		return &CreateMnemonicResponse{
			Code: mnemonicTypeErrCode,
			Msg:  mnemonicTypeErrMsg,
		}, nil
	}

	if req.Name == "" {
		return &CreateMnemonicResponse{
			Code: mnemonicNameErrCode,
			Msg:  mnemonicNameErrMsg,
		}, nil
	}

	log.Infow("CreateMnemonic", "name", req.Name, "mnemonic", mType.String())

	passwordKey := crypto.GenerateEncryptKey([]byte(km.password))

	mnemonic, err := key.GenerateMnemonic(mType)
	if err != nil {
		log.Warnw("CreateMnemonic: ", "err", err)
		return &CreateMnemonicResponse{
			Code: GenerateMnemonicErrCode,
			Msg:  err.Error(),
		}, nil
	}

	encryptedMnemonic, err := encryptMnemonic(mnemonic, passwordKey)
	if err != nil {
		log.Warnw("CreateMnemonic: ", "err", err)
		return &CreateMnemonicResponse{
			Code: encryptMnemonicErrCode,
			Msg:  err.Error(),
		}, nil
	}

	err = km.dao.CreateMnemonic(&dao.Mnemonic{
		Name:     req.Name,
		Mnemonic: encryptedMnemonic,
	})

	if err != nil {
		log.Warnw("CreateMnemonic: ", "err", err)
		return &CreateMnemonicResponse{
			Code: dbErrCode,
			Msg:  err.Error(),
		}, nil
	}

	km.mnemonics[req.Name] = mnemonic

	return &CreateMnemonicResponse{
		Code: okCode,
		Msg:  okMsg,
	}, nil
}
