// Package diagnostics provides primitives to interact with the openapi HTTP API.
//
// Code generated by github.com/deepmap/oapi-codegen version v1.15.0 DO NOT EDIT.
package diagnostics

import (
	"context"
	"encoding/json"
	"fmt"
	"io"
	"net/http"
	"net/url"
	"strings"
)

// ConnectedPeer information on a single connected peer
type ConnectedPeer struct {
	// Address domain or IP address of connected node
	Address string `json:"address"`

	// Authenticated True if NodeDID and certificate are correctly configured
	Authenticated bool `json:"authenticated"`

	// Id PeerID aka UUID of a node
	Id string `json:"id"`

	// Nodedid NodeDID if connection is authenticated
	Nodedid *string `json:"nodedid,omitempty"`
}

// Diagnostics defines model for Diagnostics.
type Diagnostics struct {
	// Network network and connection diagnostics
	Network Network `json:"network"`

	// Status characteristics of running process
	Status Status `json:"status"`

	// Vcr key numbers on credentials
	Vcr VCR `json:"vcr"`

	// Vdr key numbers on DID Documents
	Vdr VDR `json:"vdr"`
}

// Health defines model for Health.
type Health struct {
	// Details Map of the performed health checks and their results.
	Details map[string]HealthCheckResult `json:"details"`

	// Status Overall status derived from performed health checks. Values are "UP", "DOWN" and "UNKNOWN".
	Status string `json:"status"`
}

// HealthCheckResult defines model for HealthCheckResult.
type HealthCheckResult struct {
	// Details Details of the health check result.
	Details *interface{} `json:"details,omitempty"`

	// Status Status of the health check. Values are "UP", "DOWN" and "UNKNOWN".
	Status string `json:"status"`
}

// Network network and connection diagnostics
type Network struct {
	Connections struct {
		ConnectedPeers []ConnectedPeer `json:"connected_peers"`

		// ConnectedPeersCount number of peers connected
		ConnectedPeersCount int `json:"connected_peers_count"`

		// PeerId identifier generated at startup of the node
		PeerId string `json:"peer_id"`
	} `json:"connections"`

	// NodeDid DID connected to the node.
	NodeDid *string `json:"node_did,omitempty"`

	// State Key numbers of the DAG
	State struct {
		// DagLcHigh highest LC value
		DagLcHigh int `json:"dag_lc_high"`

		// DagXor XOR value of all transaction refs
		DagXor string `json:"dag_xor"`

		// FailedEvents number of failed internal events
		FailedEvents int `json:"failed_events"`

		// StoredDatabaseSizeBytes size of the DB in bytes
		StoredDatabaseSizeBytes int `json:"stored_database_size_bytes"`

		// TransactionCount number of transactions on the network
		TransactionCount int `json:"transaction_count"`
	} `json:"state"`
}

// Status characteristics of running process
type Status struct {
	// GitCommit hash of latest commit in github used to build the current binary
	GitCommit string `json:"git_commit"`

	// OsArch System architecture (arm,amd64, etc)
	OsArch string `json:"os_arch"`

	// SoftwareVersion Github tag or branch
	SoftwareVersion string `json:"software_version"`

	// Uptime Nanoseconds of uptime
	Uptime int `json:"uptime"`
}

// VCR key numbers on credentials
type VCR struct {
	// CredentialCount total number of observed credentials
	CredentialCount int `json:"credential_count"`

	// Issuer numbers on issued credentials
	Issuer struct {
		// IssuedCredentialsCount number of issued credentials from this node
		IssuedCredentialsCount int `json:"issued_credentials_count"`

		// RevokedCredentialsCount number of revoked credentials from this node
		RevokedCredentialsCount int `json:"revoked_credentials_count"`
	} `json:"issuer"`
	Verifier struct {
		// RevocationsCount total number of revocations in the network
		RevocationsCount int `json:"revocations_count"`
	} `json:"verifier"`
}

// VDR key numbers on DID Documents
type VDR struct {
	// ConflictedDidDocuments numbers on conflicted DID documents
	ConflictedDidDocuments struct {
		// OwnedCount number of conflicted documents that are under this node's control
		OwnedCount int `json:"owned_count"`

		// TotalCount total number of conflicted documents
		TotalCount int `json:"total_count"`
	} `json:"conflicted_did_documents"`

	// DidDocumentsCount total number of DID Documents
	DidDocumentsCount int `json:"did_documents_count"`
}

// RequestEditorFn  is the function signature for the RequestEditor callback function
type RequestEditorFn func(ctx context.Context, req *http.Request) error

// Doer performs HTTP requests.
//
// The standard http.Client implements this interface.
type HttpRequestDoer interface {
	Do(req *http.Request) (*http.Response, error)
}

// diagnosticsClient which conforms to the OpenAPI3 specification for this service.
type diagnosticsClient struct {
	// The endpoint of the server conforming to this interface, with scheme,
	// https://api.deepmap.com for example. This can contain a path relative
	// to the server, such as https://api.deepmap.com/dev-test, and all the
	// paths in the swagger spec will be appended to the server.
	Server string

	// Doer for performing requests, typically a *http.Client with any
	// customized settings, such as certificate chains.
	Client HttpRequestDoer

	// A list of callbacks for modifying requests which are generated before sending over
	// the network.
	RequestEditors []RequestEditorFn
}

// ClientOption allows setting custom parameters during construction
type ClientOption func(*diagnosticsClient) error

// Creates a new diagnosticsClient, with reasonable defaults
func NewClient(server string, opts ...ClientOption) (*diagnosticsClient, error) {
	// create a client with sane default values
	client := diagnosticsClient{
		Server: server,
	}
	// mutate client and add all optional params
	for _, o := range opts {
		if err := o(&client); err != nil {
			return nil, err
		}
	}
	// ensure the server URL always has a trailing slash
	if !strings.HasSuffix(client.Server, "/") {
		client.Server += "/"
	}
	// create httpClient, if not already present
	if client.Client == nil {
		client.Client = &http.Client{}
	}
	return &client, nil
}

// WithHTTPClient allows overriding the default Doer, which is
// automatically created using http.Client. This is useful for tests.
func WithHTTPClient(doer HttpRequestDoer) ClientOption {
	return func(c *diagnosticsClient) error {
		c.Client = doer
		return nil
	}
}

// WithRequestEditorFn allows setting up a callback function, which will be
// called right before sending the request. This can be used to mutate the request.
func WithRequestEditorFn(fn RequestEditorFn) ClientOption {
	return func(c *diagnosticsClient) error {
		c.RequestEditors = append(c.RequestEditors, fn)
		return nil
	}
}

// The interface specification for the client above.
type ClientInterface interface {
	// CheckHealth request
	CheckHealth(ctx context.Context, reqEditors ...RequestEditorFn) (*http.Response, error)

	// Diagnostics request
	Diagnostics(ctx context.Context, reqEditors ...RequestEditorFn) (*http.Response, error)
}

func (c *diagnosticsClient) CheckHealth(ctx context.Context, reqEditors ...RequestEditorFn) (*http.Response, error) {
	req, err := NewCheckHealthRequest(c.Server)
	if err != nil {
		return nil, err
	}
	req = req.WithContext(ctx)
	if err := c.applyEditors(ctx, req, reqEditors); err != nil {
		return nil, err
	}
	return c.Client.Do(req)
}

func (c *diagnosticsClient) Diagnostics(ctx context.Context, reqEditors ...RequestEditorFn) (*http.Response, error) {
	req, err := NewDiagnosticsRequest(c.Server)
	if err != nil {
		return nil, err
	}
	req = req.WithContext(ctx)
	if err := c.applyEditors(ctx, req, reqEditors); err != nil {
		return nil, err
	}
	return c.Client.Do(req)
}

// NewCheckHealthRequest generates requests for CheckHealth
func NewCheckHealthRequest(server string) (*http.Request, error) {
	var err error

	serverURL, err := url.Parse(server)
	if err != nil {
		return nil, err
	}

	operationPath := fmt.Sprintf("/health")
	if operationPath[0] == '/' {
		operationPath = "." + operationPath
	}

	queryURL, err := serverURL.Parse(operationPath)
	if err != nil {
		return nil, err
	}

	req, err := http.NewRequest("GET", queryURL.String(), nil)
	if err != nil {
		return nil, err
	}

	return req, nil
}

// NewDiagnosticsRequest generates requests for Diagnostics
func NewDiagnosticsRequest(server string) (*http.Request, error) {
	var err error

	serverURL, err := url.Parse(server)
	if err != nil {
		return nil, err
	}

	operationPath := fmt.Sprintf("/status/diagnostics")
	if operationPath[0] == '/' {
		operationPath = "." + operationPath
	}

	queryURL, err := serverURL.Parse(operationPath)
	if err != nil {
		return nil, err
	}

	req, err := http.NewRequest("GET", queryURL.String(), nil)
	if err != nil {
		return nil, err
	}

	return req, nil
}

func (c *diagnosticsClient) applyEditors(ctx context.Context, req *http.Request, additionalEditors []RequestEditorFn) error {
	for _, r := range c.RequestEditors {
		if err := r(ctx, req); err != nil {
			return err
		}
	}
	for _, r := range additionalEditors {
		if err := r(ctx, req); err != nil {
			return err
		}
	}
	return nil
}

// ClientWithResponses builds on ClientInterface to offer response payloads
type ClientWithResponses struct {
	ClientInterface
}

// NewClientWithResponses creates a new ClientWithResponses, which wraps
// Client with return type handling
func NewClientWithResponses(server string, opts ...ClientOption) (*ClientWithResponses, error) {
	client, err := NewClient(server, opts...)
	if err != nil {
		return nil, err
	}
	return &ClientWithResponses{client}, nil
}

// WithBaseURL overrides the baseURL.
func WithBaseURL(baseURL string) ClientOption {
	return func(c *diagnosticsClient) error {
		newBaseURL, err := url.Parse(baseURL)
		if err != nil {
			return err
		}
		c.Server = newBaseURL.String()
		return nil
	}
}

// ClientWithResponsesInterface is the interface specification for the client with responses above.
type ClientWithResponsesInterface interface {
	// CheckHealthWithResponse request
	CheckHealthWithResponse(ctx context.Context, reqEditors ...RequestEditorFn) (*CheckHealthResponse, error)

	// DiagnosticsWithResponse request
	DiagnosticsWithResponse(ctx context.Context, reqEditors ...RequestEditorFn) (*DiagnosticsResponse, error)
}

type CheckHealthResponse struct {
	Body         []byte
	HTTPResponse *http.Response
	JSON200      *Health
	JSON503      *Health
}

// Status returns HTTPResponse.Status
func (r CheckHealthResponse) Status() string {
	if r.HTTPResponse != nil {
		return r.HTTPResponse.Status
	}
	return http.StatusText(0)
}

// StatusCode returns HTTPResponse.StatusCode
func (r CheckHealthResponse) StatusCode() int {
	if r.HTTPResponse != nil {
		return r.HTTPResponse.StatusCode
	}
	return 0
}

type DiagnosticsResponse struct {
	Body         []byte
	HTTPResponse *http.Response
	JSON200      *Diagnostics
}

// Status returns HTTPResponse.Status
func (r DiagnosticsResponse) Status() string {
	if r.HTTPResponse != nil {
		return r.HTTPResponse.Status
	}
	return http.StatusText(0)
}

// StatusCode returns HTTPResponse.StatusCode
func (r DiagnosticsResponse) StatusCode() int {
	if r.HTTPResponse != nil {
		return r.HTTPResponse.StatusCode
	}
	return 0
}

// CheckHealthWithResponse request returning *CheckHealthResponse
func (c *ClientWithResponses) CheckHealthWithResponse(ctx context.Context, reqEditors ...RequestEditorFn) (*CheckHealthResponse, error) {
	rsp, err := c.CheckHealth(ctx, reqEditors...)
	if err != nil {
		return nil, err
	}
	return ParseCheckHealthResponse(rsp)
}

// DiagnosticsWithResponse request returning *DiagnosticsResponse
func (c *ClientWithResponses) DiagnosticsWithResponse(ctx context.Context, reqEditors ...RequestEditorFn) (*DiagnosticsResponse, error) {
	rsp, err := c.Diagnostics(ctx, reqEditors...)
	if err != nil {
		return nil, err
	}
	return ParseDiagnosticsResponse(rsp)
}

// ParseCheckHealthResponse parses an HTTP response from a CheckHealthWithResponse call
func ParseCheckHealthResponse(rsp *http.Response) (*CheckHealthResponse, error) {
	bodyBytes, err := io.ReadAll(rsp.Body)
	defer func() { _ = rsp.Body.Close() }()
	if err != nil {
		return nil, err
	}

	response := &CheckHealthResponse{
		Body:         bodyBytes,
		HTTPResponse: rsp,
	}

	switch {
	case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 200:
		var dest Health
		if err := json.Unmarshal(bodyBytes, &dest); err != nil {
			return nil, err
		}
		response.JSON200 = &dest

	case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 503:
		var dest Health
		if err := json.Unmarshal(bodyBytes, &dest); err != nil {
			return nil, err
		}
		response.JSON503 = &dest

	}

	return response, nil
}

// ParseDiagnosticsResponse parses an HTTP response from a DiagnosticsWithResponse call
func ParseDiagnosticsResponse(rsp *http.Response) (*DiagnosticsResponse, error) {
	bodyBytes, err := io.ReadAll(rsp.Body)
	defer func() { _ = rsp.Body.Close() }()
	if err != nil {
		return nil, err
	}

	response := &DiagnosticsResponse{
		Body:         bodyBytes,
		HTTPResponse: rsp,
	}

	switch {
	case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 200:
		var dest Diagnostics
		if err := json.Unmarshal(bodyBytes, &dest); err != nil {
			return nil, err
		}
		response.JSON200 = &dest

	}

	return response, nil
}
