package alipay

import (
	"fmt"
	"sync"
)

type CertConfig struct {
	MchCertSN  string
	RootCertSN string
	PublicKey  string
}

type manager struct {
	once        sync.Once
	mutex       sync.RWMutex
	CertConfigs map[string]*CertConfig
}

var instance manager

func getCertConfig(appId string) *CertConfig {
	c, ok := instance.CertConfigs[appId]
	if !ok {
		return nil
	}
	return c
}

func setCertConfig(appId string, certConfig *CertConfig) {
	instance.mutex.Lock()
	defer instance.mutex.Unlock()
	instance.CertConfigs[appId] = certConfig
}

func init() {
	instance.CertConfigs = make(map[string]*CertConfig)
}

func GetCert(mchCertPath, rootCertPath, PublicKeyPath, appId string) (*CertConfig, error) {
	if mchCertPath == "" || rootCertPath == "" || appId == "" {
		return nil, fmt.Errorf("mchCertPath or rootCertPath or appId is empty")
	}
	c := getCertConfig(appId)
	if c != nil {
		return nil, fmt.Errorf("appId %s already exists", appId)
	}
	mchCertSN, err := getMchCertSN(mchCertPath)
	if err != nil {
		return nil, fmt.Errorf("get mchCertSN error: %v", err)
	}
	rootCertSN, err := getRootCertSN(rootCertPath)
	if err != nil {
		return nil, fmt.Errorf("get rootCertSN error: %v", err)
	}
	publicKey, err := getPublicKey(PublicKeyPath)
	if err != nil {
		return nil, fmt.Errorf("get publicKey error: %v", err)
	}
	c = &CertConfig{
		MchCertSN:  mchCertSN,
		RootCertSN: rootCertSN,
		PublicKey:  publicKey,
	}
	setCertConfig(appId, c)
	return c, nil
}