package common

import (
	b64 "encoding/base64"

	"github.com/fiskerinc/cloud-services/pkg/common/dbbasemodel"
)

type FileKey struct {
	FileID string `pg:",pk" validate:"required,len=16,hexadecimal"`
	Key    []byte `pg:",notnull" validate:"required"`
	Auth   []byte `pg:",notnull" validate:"required"`
	Nonce  []byte `pg:",notnull" validate:"required"`
	Error  string `pg:"-"`
	dbbasemodel.DBModelBase
}

type FileKeysRequest struct {
	FileIDs []string `json:"file_ids" validate:"required,dive,len=16,hexadecimal"`
}

type FileKeyResponse struct {
	FileID string `json:"file_id" redis:"file_id" validate:"required,len=16,hexadecimal"`
	Key    string `json:"key,omitempty" redis:"key,omitempty" validate:"required"`
	Auth   string `json:"auth,omitempty" redis:"auth,omitempty" validate:"required"`
	Nonce  string `json:"nonce,omitempty" redis:"nonce,omitempty" validate:"required"`
	Error  string `json:"error,omitempty" redis:"error,omitempty"`
}

// Turns the FileKey into a FileKeyResponse
func (fkr *FileKeyResponse) Apply(key *FileKey) {
	fkr.FileID = key.FileID
	fkr.Key = b64.StdEncoding.EncodeToString(key.Key)
	fkr.Auth = b64.StdEncoding.EncodeToString(key.Auth)
	fkr.Nonce = b64.StdEncoding.EncodeToString(key.Nonce)
}

// Turns a FileKeyResponse into a file key
func (key *FileKey) Apply(fkr *FileKeyResponse) (err error) {
	key.FileID = fkr.FileID
	key.Error = fkr.Error
	key.Key, err = b64.StdEncoding.DecodeString(fkr.Key)
	if err != nil {
		return err
	}
	key.Auth, err = b64.StdEncoding.DecodeString(fkr.Auth)
	if err != nil {
		return err
	}
	key.Nonce, err = b64.StdEncoding.DecodeString(fkr.Nonce)
	return err
}
