// Copyright (C) 2019-2025, Lux Industries Inc. All rights reserved.
// See the file LICENSE for licensing terms.

package keystore

import (
	"fmt"
	"net/http"

	"github.com/luxfi/formatting"
	"github.com/luxfi/log"
	apitypes "github.com/luxfi/api/types"
)

type service struct {
	ks *keystore
}

func (s *service) CreateUser(_ *http.Request, args *apitypes.UserPass, _ *apitypes.EmptyReply) error {
	s.ks.log.Warn("deprecated API called",
		log.String("service", "keystore"),
		log.String("method", "createUser"),
		log.String("username", args.Username),
	)

	return s.ks.CreateUser(args.Username, args.Password)
}

func (s *service) DeleteUser(_ *http.Request, args *apitypes.UserPass, _ *apitypes.EmptyReply) error {
	s.ks.log.Warn("deprecated API called",
		log.String("service", "keystore"),
		log.String("method", "deleteUser"),
		"username", args.Username,
	)

	return s.ks.DeleteUser(args.Username, args.Password)
}

type ListUsersReply struct {
	Users []string `json:"users"`
}

func (s *service) ListUsers(_ *http.Request, _ *struct{}, reply *ListUsersReply) error {
	s.ks.log.Warn("deprecated API called",
		log.String("service", "keystore"),
		log.String("method", "listUsers"),
	)

	var err error
	reply.Users, err = s.ks.ListUsers()
	return err
}

type ImportUserArgs struct {
	// The username and password of the user being imported
	apitypes.UserPass
	// The string representation of the user
	User string `json:"user"`
	// The encoding of [User] ("hex")
	Encoding formatting.Encoding `json:"encoding"`
}

func (s *service) ImportUser(_ *http.Request, args *ImportUserArgs, _ *apitypes.EmptyReply) error {
	s.ks.log.Warn("deprecated API called",
		log.String("service", "keystore"),
		log.String("method", "importUser"),
		"username", args.Username,
	)

	// Decode the user from string to bytes
	user, err := formatting.Decode(args.Encoding, args.User)
	if err != nil {
		return fmt.Errorf("couldn't decode 'user' to bytes: %w", err)
	}

	return s.ks.ImportUser(args.Username, args.Password, user)
}

type ExportUserArgs struct {
	// The username and password
	apitypes.UserPass
	// The encoding for the exported user ("hex")
	Encoding formatting.Encoding `json:"encoding"`
}

type ExportUserReply struct {
	// String representation of the user
	User string `json:"user"`
	// The encoding for the exported user ("hex")
	Encoding formatting.Encoding `json:"encoding"`
}

func (s *service) ExportUser(_ *http.Request, args *ExportUserArgs, reply *ExportUserReply) error {
	s.ks.log.Warn("deprecated API called",
		log.String("service", "keystore"),
		log.String("method", "exportUser"),
		"username", args.Username,
	)

	userBytes, err := s.ks.ExportUser(args.Username, args.Password)
	if err != nil {
		return err
	}

	// Encode the user from bytes to string
	reply.User, err = formatting.Encode(args.Encoding, userBytes)
	if err != nil {
		return fmt.Errorf("couldn't encode user to string: %w", err)
	}
	reply.Encoding = args.Encoding
	return nil
}
