package claims

import (
	"crypto/sha256"
	"encoding/pem"
	"errors"
	"fmt"
	"oc-auth/conf"
	"oc-auth/infrastructure/perms_connectors"
	"oc-auth/infrastructure/utils"
	"os"
	"strings"
	"time"

	"cloud.o-forge.io/core/oc-lib/models/peer"
	"cloud.o-forge.io/core/oc-lib/tools"
)

type HydraClaims struct{}

func (h HydraClaims) generateKey(relation string, path string) (string, error) {
	method, err := utils.ExtractMethod(relation, true)
	if err != nil {
		return "", err
	}
	p := strings.ReplaceAll(strings.ToUpper(path), "/", "_")
	return strings.ToUpper(method.String()) + "_" + strings.ReplaceAll(p, ":", ""), nil
}

// decode key expect to extract method and path from key
func (h HydraClaims) decodeKey(key string, external bool) (tools.METHOD, string, error) {
	s := strings.Split(key, "_")
	if len(s) < 2 {
		return tools.GET, "", errors.New("invalid key")
	}
	if strings.Contains(strings.ToUpper(s[0]), "INTERNAL") && external {
		return tools.GET, "", errors.New("external ask for internal key")
	}
	meth, err := utils.ExtractMethod(s[0], false)
	if err != nil {
		return meth, "", err
	}
	p := strings.ReplaceAll(strings.ToUpper(s[1]), "_", "/")
	return meth, p, nil
}

func (h HydraClaims) DecodeSignature(host string, signature string, publicKey string) (bool, error) {
	hashed := sha256.Sum256([]byte(host))
	spkiBlock, _ := pem.Decode([]byte(publicKey)) // get public key into a variable
	err := VerifyDefault(hashed[:], spkiBlock.Bytes, signature)
	if err != nil {
		return false, err
	}
	return true, nil
}

func (h HydraClaims) encodeSignature(host string) (string, error) {
	hashed := sha256.Sum256([]byte(host))
	// READ FILE TO GET PRIVATE KEY FROM PVK PEM PATH
	content, err := os.ReadFile(conf.GetConfig().PrivateKeyPath)
	if err != nil {
		return "", err
	}
	privateKey := string(content)
	spkiBlock, _ := pem.Decode([]byte(privateKey))
	return SignDefault(hashed[:], spkiBlock.Bytes)
}

func (h HydraClaims) clearBlank(path []string) []string {
	// clear blank
	newPath := []string{}
	for _, p := range path {
		if p != "" {
			newPath = append(newPath, p)
		}
	}
	return newPath
}

func (a HydraClaims) CheckExpiry(exp int64) bool {
	now := time.Now().UTC().Unix()
	return now <= exp
}

func (h HydraClaims) DecodeClaimsInToken(host string, method string, forward string, sessionClaims Claims, publicKey string, external bool) (bool, error) {
	idTokenClaims := sessionClaims.Session.IDToken
	if idTokenClaims["signature"] == nil {
		return false, errors.New("no signature found")
	}
	signature := idTokenClaims["signature"].(string)
	if ok, err := h.DecodeSignature(host, signature, publicKey); !ok {
		return false, err
	}
	claims := sessionClaims.Session.AccessToken
	path := strings.ReplaceAll(forward, "http://"+host, "")
	splittedPath := h.clearBlank(strings.Split(path, "/"))
	if _, ok := claims["exp"].(float64); !ok || !h.CheckExpiry(int64(claims["exp"].(float64))) {
		return false, errors.New("token is expired")
	}
	for m, p := range claims {
		match := true
		splittedP := h.clearBlank(strings.Split(p.(string), "/"))
		if len(splittedP) != len(splittedPath) {
			continue
		}
		for i, v := range splittedP {
			if strings.Contains(v, ":") { // is a param
				continue
			} else if v != splittedPath[i] {
				match = false
				break
			}
		}
		if match {
			meth, _, err := h.decodeKey(m, external)
			if err != nil {
				continue
			}
			perm := perms_connectors.Permission{
				Relation: "permits" + strings.ToUpper(meth.String()),
				Object:   p.(string),
			}
			return perms_connectors.GetPermissionConnector("").CheckPermission(perm, nil, true), nil
		}
	}
	return false, errors.New("no permission found")
}

// add claims to token method of HydraTokenizer
func (h HydraClaims) AddClaimsToToken(clientID string, userId string, p *peer.Peer) Claims {
	claims := Claims{}
	perms, err := perms_connectors.KetoConnector{}.GetPermissionByUser(userId, true)

	if err != nil {
		return claims
	}
	claims.Session.AccessToken = make(map[string]interface{})
	claims.Session.IDToken = make(map[string]interface{})
	fmt.Println("PERMS err 1", perms, err)
	for _, perm := range perms {
		key, err := h.generateKey(strings.ReplaceAll(perm.Relation, "permits", ""), perm.Subject)
		if err != nil {
			continue
		}
		claims.Session.AccessToken[key] = perm.Subject
	}
	sign, err := h.encodeSignature(p.Url)
	if err != nil {
		return claims
	}
	claims.Session.IDToken["username"] = userId
	claims.Session.IDToken["peer_id"] = p.UUID
	// we should get group from user
	groups, err := perms_connectors.KetoConnector{}.GetGroupByUser(userId)
	if err != nil {
		return claims
	}
	claims.Session.IDToken["client_id"] = clientID
	claims.Session.IDToken["groups"] = groups
	claims.Session.IDToken["signature"] = sign
	return claims
}
