package vehicleconfig

import (
	"encoding/json"
	"fmt"
	"io"
	"net/http"

	"github.com/fiskerinc/cloud-services/pkg/common"
	"github.com/fiskerinc/cloud-services/pkg/httpclient"
	"github.com/fiskerinc/cloud-services/pkg/logger"
	"github.com/fiskerinc/cloud-services/pkg/utils/envtool"
	"github.com/pkg/errors"
)

func NewConfigService() ConfigServiceInterface {
	return &ConfigService{
		configURL: envtool.GetEnv("ODX_URL", "http://odx.prd.cec.internal:5000/api/v1/OdxService"),
	}
}

type ConfigServiceInterface interface {
	GetCDS(request common.VODCDSRequest) (map[string]string, error)
}

// ConfigService is currently a mock of the actual calls to the ODX parser services
type ConfigService struct {
	configURL string
}

func (cs *ConfigService) GetCDS(request common.VODCDSRequest) (map[string]string, error) {
	header := http.Header{}
	header.Add("Content-Type", "application/json")
	resp, err := httpclient.Post(cs.configURL+"/GetVodCDSCodingData", request, header)
	if err != nil {
		return nil, errors.WithStack(err)
	}

	if resp.StatusCode != http.StatusOK {
		return nil, errors.WithStack(fmt.Errorf("calling ODX failed with status: %s", resp.Status))
	}

	defer resp.Body.Close()
	respBody, err := io.ReadAll(resp.Body)
	if err != nil {
		return nil, errors.WithStack(err)
	}

	logger.Info().Msg(fmt.Sprintf("odx service has returned the next answer: %s", string(respBody)))

	respPayload := map[string]string{}
	err = json.Unmarshal(respBody, &respPayload)
	if err != nil {
		return nil, errors.WithStack(err)
	}

	return respPayload, nil
}
