package apple

import (
	"context"
	"encoding/json"
	"strings"

	"github.com/perfect-panel/server/internal/model/payment"
	"github.com/perfect-panel/server/internal/svc"
	iapapple "github.com/perfect-panel/server/pkg/iap/apple"
)

// LoadAppleServerAPIConfig loads the first enabled Apple IAP payment config
// from the payment table and returns a ServerAPIConfig ready for API calls.
func LoadAppleServerAPIConfig(ctx context.Context, svc *svc.ServiceContext) (*iapapple.ServerAPIConfig, error) {
	pays, err := svc.PaymentModel.FindListByPlatform(ctx, "apple")
	if err != nil {
		return nil, err
	}
	for _, pay := range pays {
		if pay.Enable == nil || !*pay.Enable || pay.Config == "" {
			continue
		}
		var cfg payment.AppleIAPConfig
		if e := cfg.Unmarshal([]byte(pay.Config)); e != nil {
			continue
		}
		if cfg.KeyID == "" || cfg.IssuerID == "" || cfg.PrivateKey == "" {
			continue
		}
		apiCfg := &iapapple.ServerAPIConfig{
			KeyID:      cfg.KeyID,
			IssuerID:   cfg.IssuerID,
			PrivateKey: fixPEMKey(cfg.PrivateKey),
			Sandbox:    cfg.Sandbox,
		}
		// Read BundleID from site custom data
		if svc.Config.Site.CustomData != "" {
			var customData struct {
				IapBundleId string `json:"iapBundleId"`
			}
			_ = json.Unmarshal([]byte(svc.Config.Site.CustomData), &customData)
			apiCfg.BundleID = customData.IapBundleId
		}
		return apiCfg, nil
	}
	return nil, nil
}

func fixPEMKey(key string) string {
	if !strings.Contains(key, "\n") && strings.Contains(key, "BEGIN PRIVATE KEY") {
		key = strings.ReplaceAll(key, " ", "\n")
		key = strings.ReplaceAll(key, "-----BEGIN\nPRIVATE\nKEY-----", "-----BEGIN PRIVATE KEY-----")
		key = strings.ReplaceAll(key, "-----END\nPRIVATE\nKEY-----", "-----END PRIVATE KEY-----")
	}
	return key
}
