package client

import (
	"errors"
	"fmt"
	"os"

	"github.com/BurntSushi/toml"
)

const CONFIG_PATH = ".config/oprand/"
const CONFIG_FILE = "credentials.toml"

type Credentials struct {
	Apikey    string `toml:"apikey"`
	Apisecret string `toml:"apisecret"`
}

// SetupConfig lets user input their API crendetials and
// saves them in a file. This credential file will be read
// when needed to authenticate network requests.
func (op *OprClient) SetupConfig() error {

	var config Credentials

	// Create config path if it doesn't exist, with read for user only
	fullPath := fmt.Sprintf("%s/%s", os.Getenv("HOME"), CONFIG_PATH)
	_, err := os.Stat(fullPath)
	if errors.Is(err, os.ErrNotExist) {
		err = os.MkdirAll(fullPath, 0700)
		if err != nil {
			return fmt.Errorf("cannot mkdir config file path: %w", err)
		}
	} else if err != nil {
		return fmt.Errorf("cannot stat config file path: %w", err)
	} else {
		fmt.Fprintf(os.Stderr, "WARN: Config file at `%s` already exists.\n", fullPath+CONFIG_FILE)
		fmt.Fprintf(os.Stderr, "WARN: Content will be overwritten by new values entered. Press Ctrl+C to keep current values.\n\n")
	}

	// Ask for API Key
	fmt.Printf("OPRAND API KEY: ")
	fmt.Scanln(&config.Apikey)

	// Ask for API Secret
	fmt.Printf("OPRAND API SECRET: ")
	fmt.Scanln(&config.Apisecret)

	// Write to config file
	f, err := os.OpenFile(fullPath+CONFIG_FILE, os.O_CREATE|os.O_WRONLY, 0644)
	if err != nil {
		return fmt.Errorf("cannot open config file: %w", err)
	}

	header := []byte("# Credentials to access threat data provided by oprand.com\n# Generated by: opr config\n\n")
	if _, err := f.Write(header); err != nil {
		return fmt.Errorf("cannot write to config file: %w", err)
	}

	err = toml.NewEncoder(f).Encode(&config)
	if err != nil {
		return fmt.Errorf("cannot marshall config struct to toml: %w", err)
	}

	if err := f.Close(); err != nil {
		return fmt.Errorf("cannot close config file: %w", err)
	}

	fmt.Printf("Config file successfully written at `%s`\n", fullPath+CONFIG_FILE)

	return nil
}
