package utils_test

import (
	"strings"
	"testing"
	"time"

	"github.com/golang-jwt/jwt/v5"
	"github.com/stretchr/testify/assert"
	"penahub.gitlab.yandexcloud.net/pena-services/customer/internal/models"
	"penahub.gitlab.yandexcloud.net/pena-services/customer/internal/utils"
)

func TestJWT(t *testing.T) {
	type user struct {
		Name string `json:"name"`
		Age  int    `json:"age"`
	}

	testUser := user{
		Name: "test",
		Age:  80,
	}

	publicKey := `-----BEGIN PUBLIC KEY-----
		MIICIjANBgkqhkiG9w0BAQEFAAOCAg8AMIICCgKCAgEAyt4XuLovUY7i12K2PIMb
		QZOKn+wFFKUvxvKQDel049/+VMpHMx1FLolUKuyGp9zi6gOwjHsBPgc9oqr/eaXG
		QSh7Ult7i9f+Ht563Y0er5UU9Zc5ZPSxf9O75KYD48ruGkqiFoncDqPENK4dtUa7
		w0OqlN4bwVBbmIsP8B3EDC5Dof+vtiNTSHSXPx+zifKeZGyknp+nyOHVrRDhPjOh
		zQzCom0MSZA/sJYmps8QZgiPA0k4Z6jTupDymPOIwYeD2C57zSxnAv0AfC3/pZYJ
		bZYH/0TszRzmy052DME3zMnhMK0ikdN4nzYqU0dkkA5kb5GtKDymspHIJ9eWbUuw
		gtg8Rq/LrVBj1I3UFgs0ibio40k6gqinLKslc5Y1I5mro7J3OSEP5eO/XeDLOLlO
		JjEqkrx4fviI1cL3m5L6QV905xmcoNZG1+RmOg7D7cZQUf27TXqM381jkbNdktm1
		JLTcMScxuo3vaRftnIVw70V8P8sIkaKY8S8HU1sQgE2LB9t04oog5u59htx2FHv4
		B13NEm8tt8Tv1PexpB4UVh7PIualF6SxdFBrKbraYej72wgjXVPQ0eGXtGGD57j8
		DUEzk7DK2OvIWhehlVqtiRnFdAvdBj2ynHT2/5FJ/Zpd4n5dKGJcQvy1U1qWMs+8
		M7AHfWyt2+nZ04s48+bK3yMCAwEAAQ==
	-----END PUBLIC KEY-----`

	privateKey := `-----BEGIN RSA PRIVATE KEY-----
		MIIJKQIBAAKCAgEAyt4Xu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replace(publicKey, "\t", "", -1)
	privateKey = strings.Replace(privateKey, "\t", "", -1)

	jwt := utils.NewJWT(&models.JWTConfiguration{
		PrivateKey: privateKey,
		PublicKey:  publicKey,
		Algorithm:  *jwt.SigningMethodRS256,
		ExpiresIn:  15 * time.Minute,
		Issuer:     "issuer1",
		Audience:   "audience1",
	})

	t.Run("Успешная генерация токена", func(t *testing.T) {
		assert.NotPanics(t, func() {
			token, err := jwt.Create(testUser.Name)

			assert.NoError(t, err)
			assert.NotZero(t, token)
			assert.NotEmpty(t, token)
		})
	})

	t.Run("Успешная валидация токена", func(t *testing.T) {
		assert.NotPanics(t, func() {
			token, err := jwt.Create(testUser.Name)

			isNoError := assert.NoError(t, err)

			if isNoError {
				parsedUser, err := jwt.Validate(token)

				assert.NoError(t, err)
				assert.NotNil(t, parsedUser)
				assert.Equal(t, testUser.Name, parsedUser)
			}
		})
	})
}
