package decortsdk

import (
	"context"
	"encoding/json"
	"errors"
	"fmt"
	"net/http"
	"strings"

	"repository.basistech.ru/BASIS/decort-golang-sdk/internal/constants"
)

type CheckInfo struct {
	Version string `json:"version"`
	Build   uint64 `json:"build"`
}

const versionURL = "/system/info/version"

func (de DecortClient) Check() (*CheckInfo, error) {
	res, err := de.DecortApiCall(context.Background(), http.MethodGet, versionURL, nil)
	if err != nil {
		return nil, err
	}

	info := CheckInfo{}

	err = json.Unmarshal([]byte(strings.Replace(strings.Trim(string(res), `"`), "\\", "", -1)), &info)
	if err != nil {
		var v string
		json.Unmarshal([]byte(res), &v)
		if _, exists := constants.VersionMap[v]; exists {
			info.Version = v
		} else {
			return nil, fmt.Errorf("platform version isn't supported")
		}
	}

	if v, ok := constants.VersionMap[info.Version]; ok {
		if v == "-" {
			return &info, nil
		}
		return nil, errors.New(fmt.Sprintf("SDK don't support platform version %s, please use %s SDK version", info.Version, v))
	}

	return nil, errors.New(fmt.Sprintf("platform version %s isn't supported", info.Version))
}

func (bvs BVSDecortClient) Check() (*CheckInfo, error) {
	res, err := bvs.DecortApiCall(context.Background(), http.MethodGet, versionURL, nil)
	if err != nil {
		return nil, err
	}

	info := CheckInfo{}

	err = json.Unmarshal([]byte(strings.Replace(strings.Trim(string(res), `"`), "\\", "", -1)), &info)
	if err != nil {
		var v string
		json.Unmarshal([]byte(res), &v)
		if _, exists := constants.VersionMap[v]; exists {
			info.Version = v
		} else {
			return nil, fmt.Errorf("platform version isn't supported")
		}
	}

	if v, ok := constants.VersionMap[info.Version]; ok {
		if v == "-" {
			return &info, nil
		}
		return nil, errors.New(fmt.Sprintf("SDK don't support platform version %s, please use %s SDK version", info.Version, v))
	}

	return nil, errors.New(fmt.Sprintf("platform version %s isn't supported", info.Version))
}

func (ldc LegacyDecortClient) Check() (*CheckInfo, error) {
	res, err := ldc.DecortApiCall(context.Background(), http.MethodGet, versionURL, nil)
	if err != nil {
		return nil, err
	}

	info := CheckInfo{}

	err = json.Unmarshal([]byte(strings.Replace(strings.Trim(string(res), `"`), "\\", "", -1)), &info)
	if err != nil {
		var v string
		json.Unmarshal([]byte(res), &v)
		if _, exists := constants.VersionMap[v]; exists {
			info.Version = v
		} else {
			return nil, fmt.Errorf("platform version isn't supported")
		}
	}

	if v, ok := constants.VersionMap[info.Version]; ok {
		if v == "-" {
			return &info, nil
		}
		return nil, errors.New(fmt.Sprintf("SDK don't support platform version %s, please use %s SDK version", info.Version, v))
	}

	return nil, errors.New(fmt.Sprintf("platform version %s isn't supported", info.Version))
}
