package tmobile

import (
	"os"
	"strings"

	"github.com/fiskerinc/cloud-services/pkg/logger"

	"github.com/pkg/errors"
)

const pfx = "-----BEGIN PRIVATE KEY-----"

func AsFileIfText(envVal string) (*os.File, error) {
	if strings.HasPrefix(envVal, pfx) {
		f, err := os.CreateTemp("/tmp", "pk*.pkcs8")
		if err != nil {
			return nil, errors.WithMessage(err, "failed to create temp file")
		}

		_, err = f.WriteString(envVal)
		if err != nil {
			return nil, errors.WithMessage(err, "failed to write to temp file")
		}

		return f, nil
	}
	if _, err := os.Stat(envVal); err != nil {
		return nil, errors.WithMessage(err, "failed to stat file")
	}

	return nil, nil
}

func pkPathVal(f *os.File, pkVal string) string {
	if f != nil {
		return f.Name()
	}

	return pkVal
}

func tempFilCloseDelete(f *os.File) {
	if err := f.Close(); err != nil {
		logger.Warn().Err(err).Msg("failed to close temp file")
	}

	if err := os.Remove(f.Name()); err != nil {
		logger.Warn().Err(err).Msg("failed to remove temp file")
	}
}

func ToXAuthOriginator(accessToken string) string {
	arr := strings.Split(accessToken, "Bearer ")
	if len(arr) < 1 {
		return ""
	}
	return arr[1]
}
