package config

import (
	"encoding/json"
	"os"
	"time"

	"gopkg.in/yaml.v3"
	"repository.basistech.ru/BASIS/decort-golang-sdk/internal/serialization"
	"repository.basistech.ru/BASIS/decort-golang-sdk/internal/validators"
)

type BVSConfig struct {
	// ServiceAccount username
	// Required: true
	// Example : "osh_mikoev"
	Username string `json:"username" yaml:"username" validate:"required"`

	// ServiceAccount password
	// Required: true
	// Example: "[1o>hYkjnJr)HI78q7t&#%8Lm"
	Password string `json:"password" yaml:"password" validate:"required"`

	// Domain name
	// Required: true
	// Example: "dynamix"
	Domain string `json:"domain" yaml:"domain" validate:"required"`

	// Application (client) identifier for authorization
	// in the cloud platform controller in oauth2 mode.
	// Required: true
	// Example: "ewqfrvea7s890avw804389qwguf234h0otfi3w4eiu"
	AppID string `json:"appId" yaml:"appId" validate:"required"`

	// Application (client) secret code for authorization
	// in the cloud platform controller in oauth2 mode.
	// Example: "frvet09rvesfis0c9erv9fsov0vsdfi09ovds0f"
	AppSecret string `json:"appSecret" yaml:"appSecret" validate:"required"`

	// Platform authentication service address
	// Required: true
	// Example: "https://sso.digitalenergy.online"
	SSOURL string `json:"ssoUrl" yaml:"ssoUrl" validate:"url"`

	// The address of the platform on which the actions are planned
	// Required: true
	// Example: "https://mr4.digitalenergy.online"
	DecortURL string `json:"decortUrl" yaml:"decortUrl" validate:"url"`

	// JWT platform token
	// Required: false
	// Example: "qwqwdfwv68979we0q9bfv7e9sbvd89798qrwv97ff"
	Token Token `json:"token" yaml:"token"`

	// Amount platform request attempts
	// Default value: 5
	// Required: false
	Retries uint64 `json:"retries" yaml:"retries"`

	// Skip verify
	// Required: false
	SSLSkipVerify bool `json:"sslSkipVerify" yaml:"sslSkipVerify"`

	// HTTP client timeout, unlimited if left empty
	// Required: false
	Timeout Duration `json:"timeout" yaml:"timeout"`

	// The path of the configuration file entry
	// Required: false
	PathCfg string `json:"path_cfg" yaml:"path_cfg"`

	// The path of the token file entry
	// Required: false
	PathToken string `json:"path_token" yaml:"path_token"`

	// The number of minutes before the expiration of the token, a refresh will be made
	// Required: false
	TimeToRefresh int64 `json:"timeToRefresh" yaml:"timeToRefresh"`
}

type Token struct {
	// AccessToken is the token that authorizes and authenticates
	// the requests.
	// Required: false
	AccessToken string `json:"access_token" yaml:"access_token"`

	// TokenType is the type of token.
	// The Type method returns either this or "Bearer", the default.
	// Required: false
	TokenType string `json:"token_type" yaml:"token_type"`

	// RefreshToken is a token that's used by the application
	// (as opposed to the user) to refresh the access token
	// if it expires.
	// Required: false
	RefreshToken string `json:"refresh_token" yaml:"refresh_token"`

	// Expiry is the optional expiration time of the access token.
	// Required: false
	Expiry time.Time `json:"expiry" yaml:"expiry"`
}

// SetTimeout is used to set HTTP client timeout.
func (c *BVSConfig) SetTimeout(dur time.Duration) {
	c.Timeout = Duration(dur)
}

// ParseConfigJSON parses Config from specified JSON-formatted file.
func ParseConfigBVSJSON(path string) (BVSConfig, error) {
	file, err := os.ReadFile(path)
	if err != nil {
		return BVSConfig{}, err
	}

	var config BVSConfig

	err = json.Unmarshal(file, &config)
	if err != nil {
		return BVSConfig{}, err
	}

	err = validators.ValidateConfig(config)
	if err != nil {
		return BVSConfig{}, validators.ValidationErrors(validators.GetErrors(err))
	}

	return config, nil
}

// ParseConfigJSON parses Token from specified JSON-formatted file.
func ParseTokenBVSJSON(path string) (Token, error) {
	file, err := os.ReadFile(path)
	if err != nil {
		return Token{}, err
	}

	var token Token

	err = json.Unmarshal(file, &token)
	if err != nil {
		return Token{}, err
	}

	err = validators.ValidateConfig(token)
	if err != nil {
		return Token{}, validators.ValidationErrors(validators.GetErrors(err))
	}

	return token, nil
}

// ParseTokenBVSYAML parses Token from specified YAML-formatted file.
func ParseTokenBVSYAML(path string) (Token, error) {
	file, err := os.ReadFile(path)
	if err != nil {
		return Token{}, err
	}

	var token Token

	err = yaml.Unmarshal(file, &token)
	if err != nil {
		return Token{}, err
	}

	err = validators.ValidateConfig(token)
	if err != nil {
		return Token{}, validators.ValidationErrors(validators.GetErrors(err))
	}

	return token, nil
}

// ParseConfigYAML parses Config from specified YAML-formatted file.
func ParseConfigBVSYAML(path string) (BVSConfig, error) {
	file, err := os.ReadFile(path)
	if err != nil {
		return BVSConfig{}, err
	}

	var config BVSConfig

	err = yaml.Unmarshal(file, &config)
	if err != nil {
		return BVSConfig{}, err
	}

	err = validators.ValidateConfig(config)
	if err != nil {
		return BVSConfig{}, validators.ValidationErrors(validators.GetErrors(err))
	}

	return config, nil
}

func (t Token) Serialize(params ...string) (serialization.Serialized, error) {
	if len(params) > 1 {
		prefix := params[0]
		indent := params[1]

		return json.MarshalIndent(t, prefix, indent)
	}

	return json.Marshal(t)
}

func (c BVSConfig) Serialize(params ...string) (serialization.Serialized, error) {
	if len(params) > 1 {
		prefix := params[0]
		indent := params[1]

		return json.MarshalIndent(c, prefix, indent)
	}

	return json.Marshal(c)
}
