package jwtutil

import (
	"Yimaru-Backend/internal/domain"
	"errors"
	"fmt"
	"time"

	"github.com/golang-jwt/jwt/v5"
)

var (
	ErrExpiredToken         = errors.New("token expired")
	ErrMalformedToken       = errors.New("token malformed")
	ErrTokenNotExpired      = errors.New("token not expired")
	ErrRefreshTokenNotFound = errors.New("refresh token not found")
)

type UserClaim struct {
	jwt.RegisteredClaims
	UserId    int64
	Role      domain.Role
	CompanyID domain.NullJwtInt64
}

type JwtConfig struct {
	JwtAccessKey    string
	JwtAccessExpiry int
}

func CreateJwt(userId int64, Role domain.Role, key string, expiry int) (string, error) {
	token := jwt.NewWithClaims(jwt.SigningMethodHS256, UserClaim{
		RegisteredClaims: jwt.RegisteredClaims{
			Issuer:    "yimaru.com",
			IssuedAt:  jwt.NewNumericDate(time.Now()),
			Audience:  jwt.ClaimStrings{"api.yimaru.com"},
			NotBefore: jwt.NewNumericDate(time.Now()),
			ExpiresAt: jwt.NewNumericDate(time.Now().Add(time.Duration(expiry) * time.Second)),
		},
		UserId: userId,
		Role:   Role,
		// CompanyID: domain.NullJwtInt64{
		// 	Value: CompanyID.Value,
		// 	Valid: CompanyID.Valid,
		// },
	})
	jwtToken, err := token.SignedString([]byte(key))
	return jwtToken, err
}

func ParseJwt(jwtToken string, key string) (*UserClaim, error) {
	token, err := jwt.ParseWithClaims(jwtToken, &UserClaim{}, func(token *jwt.Token) (interface{}, error) {
		return []byte(key), nil
	})
	if err != nil {
		if errors.Is(err, jwt.ErrTokenExpired) {
			return nil, ErrExpiredToken
		}
		if errors.Is(err, jwt.ErrTokenMalformed) {
			fmt.Printf("error %v", err.Error())
			return nil, ErrMalformedToken
		}
		return nil, err
	}
	if claims, ok := token.Claims.(*UserClaim); ok && token.Valid {
		return claims, nil
	}
	return nil, errors.New("invalid token claims")
}
