package handler

import (
	"context"
	"kontor-api-echo/pkg/schema"
	"kontor-api-echo/pkg/utils"
	"net/http"
	"time"

	"github.com/golang-jwt/jwt/v5"
	"github.com/labstack/echo/v4"
	"github.com/uptrace/bun"
)

type jwtCustomClaims struct {
	Name  string `json:"name"`
	Admin bool   `json:"admin"`
	jwt.RegisteredClaims
}

type LoginRequest struct {
	Email    string `json:"email"`
	Password string `json:"password"`
}

func Login(c echo.Context) error {
	// user := c.FormValue("email")
	// pass := c.FormValue("password")
	loginRequest := new(LoginRequest)
	if err := c.Bind(loginRequest); err != nil {
		return err
	}

	email := loginRequest.Email
	password := loginRequest.Password

	var profile schema.Profile
	var err error
	var db *bun.DB
	ctx := context.Background()

	db, _ = schema.GetDatabase()
	err = db.NewSelect().Model(&profile).Where("email = ?", email).Scan(ctx)
	if err != nil {
		return c.String(http.StatusInternalServerError, err.Error())
	}

	if !utils.ComparePassword(profile.Password, password) {
		return echo.ErrUnauthorized
	}

	// Set custom claims
	claims := &jwtCustomClaims{
		"Jon Snow",
		true,
		jwt.RegisteredClaims{
			ExpiresAt: jwt.NewNumericDate(time.Now().Add(time.Hour * 72)),
		},
	}

	// Create token with claims
	token := jwt.NewWithClaims(jwt.SigningMethodHS256, claims)

	// Generate encoded token and send it as response.
	t, err := token.SignedString([]byte("secret"))
	if err != nil {
		return err
	}

	return c.JSON(http.StatusOK, echo.Map{"access_token": t, "token_type": "bearer"})
}

func restricted(c echo.Context) error {
	user := c.Get("user").(*jwt.Token)
	claims := user.Claims.(*jwtCustomClaims)
	name := claims.Name
	return c.String(http.StatusOK, "Welcome "+name+"!")
}
