package apple

import (
	"encoding/json"
	"strings"
)

type NotificationEnvelope struct {
	NotificationType string
	TransactionJWS   string
}

func ParseNotificationSignedPayload(jws string) (*NotificationEnvelope, error) {
	parts := strings.Split(strings.TrimSpace(jws), ".")
	if len(parts) != 3 {
		return nil, ErrInvalidJWS
	}
	data, err := decodeB64URL(parts[1])
	if err != nil {
		return nil, err
	}
	var raw map[string]interface{}
	if err = json.Unmarshal(data, &raw); err != nil {
		return nil, err
	}
	env := &NotificationEnvelope{}
	if v, ok := raw["notificationType"].(string); ok {
		env.NotificationType = v
	}
	if d, ok := raw["data"].(map[string]interface{}); ok {
		if sjws, ok := d["signedTransactionInfo"].(string); ok {
			env.TransactionJWS = sjws
		}
	}
	return env, nil
}

func VerifyNotificationSignedPayload(jws string) (*TransactionPayload, string, error) {
	env, err := ParseNotificationSignedPayload(jws)
	if err != nil {
		return nil, "", err
	}
	if env.TransactionJWS == "" {
		return nil, env.NotificationType, ErrInvalidJWS
	}
	tx, err := VerifyTransactionJWS(env.TransactionJWS)
	if err != nil {
		return nil, env.NotificationType, err
	}
	return tx, env.NotificationType, nil
}
