package auth

import (
	"crypto/sha1"
	"encoding/base64"
	"github.com/gin-gonic/gin"
	"github.com/golang-jwt/jwt/v5"
	"net/http"
	"time"
)

type SignReq struct {
	Email    string `json:"email"`
	Password string `json:"password"`
}
type User struct {
	Id          string `json:"id"`
	DisplayName string `json:"displayName"`
	PhotoURL    string `json:"photoURL"`
	PhoneNumber string `json:"phoneNumber"`
	Country     string `json:"country"`
	Address     string `json:"address"`
	State       string `json:"state"`
	City        string `json:"city"`
	ZipCode     string `json:"zipCode"`
	About       string `json:"about"`
	Role        string `json:"role"`
	IsPublic    bool   `json:"isPublic"`
	Email       string `json:"email"`
	Password    string `json:"password"`
}

func Sign(c *gin.Context) {
	var req SignReq
	if err := c.ShouldBindJSON(&req); err != nil {
		c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
	}
	token, _ := GenToken(req.Email)
	c.JSON(http.StatusOK, gin.H{
		"accessToken": token,
		"user":        User{},
	})
}

type Token struct {
	Token       string `json:"token"`
	AccessToken string `json:"access_token"`
	ExpiresIn   int    `json:"expires_in"`
	IssuedAt    string `json:"issued_at"`
}

func DefaultToken(ip string) Token {
	acc := sha1.Sum([]byte(ip))
	access := base64.StdEncoding.EncodeToString(acc[:])
	return Token{
		Token:       access,
		AccessToken: access,
		ExpiresIn:   300,
		IssuedAt:    time.Now().Format("2006-01-02T15:04:05.999999999Z"),
	}
}
func GenToken(u string) (string, error) {
	token := jwt.NewWithClaims(jwt.SigningMethodHS256, jwt.MapClaims{
		"user": u,
		"nbf":  time.Now().Unix(),
		"exp":  time.Now().Add(time.Minute * 300).Unix(),
	})

	return token.SignedString([]byte("fasthub-center"))
}
