package userconsent

import (
	"bytes"
	"encoding/json"
	"net/http"
	"sync"

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

var (
	userConsentService UserConsentServiceInterface
	userConsentOnce    sync.Once
)

func GetUserConsentService() UserConsentServiceInterface {
	userConsentOnce.Do(func() {
		if userConsentService != nil {
			return
		}
		userConsentService = NewUserConsentService()
	})

	return userConsentService
}

func SetUserConsentService(ucs UserConsentServiceInterface) {
	userConsentService = ucs
}

func NewUserConsentService() UserConsentServiceInterface {
	return &UserConsentService{
		userConsentURL:     envtool.GetEnv("USER_CONSENT_URL", "REPLACE_ME"),
		userConsentXApiKey: envtool.GetEnv("USER_CONSENT_X_API_KEY", "REPLACE_ME"),
	}
}

type UserConsentServiceInterface interface {
	UserConsent(ucd common.UserConsentDataRequest) (*http.Response, error)
	UserConsentByVehicleNumber(vin string) (*http.Response, error)
}

type UserConsentService struct {
	userConsentURL     string
	userConsentXApiKey string
}

func (ucs *UserConsentService) UserConsent(ucd common.UserConsentDataRequest) (*http.Response, error) {
	jsonBytes, err := json.Marshal(ucd)
	if err != nil {
		return nil, err
	}

	logger.Info().Msg(string(jsonBytes))

	request, err := http.NewRequest(http.MethodPost, ucs.userConsentURL+"/user-consent", bytes.NewReader(jsonBytes))
	if err != nil {
		return nil, errors.WithStack(err)
	}
	request.Header.Add("accept", "application/json")
	request.Header.Add("x-api-key", ucs.userConsentXApiKey)
	request.Header.Add("Content-Type", "application/json")

	resp, err := http.DefaultClient.Do(request)

	return resp, errors.WithStack(err)
}

func (ucs *UserConsentService) UserConsentByVehicleNumber(vin string) (*http.Response, error) {
	ucvn := common.UserConsentByVehicleNumberRequest{VehicleNumber: vin}
	jsonBytes, err := json.Marshal(ucvn)
	if err != nil {
		return nil, errors.WithStack(err)
	}

	request, err := http.NewRequest(http.MethodPost, ucs.userConsentURL+"/user-consent/byVehicleNumber", bytes.NewReader(jsonBytes))
	if err != nil {
		return nil, errors.WithStack(err)
	}
	request.Header.Add("accept", "application/json")
	request.Header.Add("x-api-key", ucs.userConsentXApiKey)
	request.Header.Add("Content-Type", "application/json")

	resp, err := http.DefaultClient.Do(request)

	return resp, errors.WithStack(err)
}
