package users

import (
	"context"
	"encoding/json"
	"fmt"
	"io"
	"net/http"
	"time"

	core "fr.latosa-escrima/core"
	"fr.latosa-escrima/core/models"
	"github.com/golang-jwt/jwt/v5"
)

var MySigningKey = []byte("COUCOU")

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

type Claims struct {
	UserID string `json:"user_id"`
	jwt.RegisteredClaims
}

func HandleLogin(w http.ResponseWriter, r *http.Request) {
	if r.Body == nil {
		core.JSONError{
			Status:  core.Error,
			Message: "No body has been provided.",
		}.Respond(w, http.StatusNoContent)
		return
	}

	body, err := io.ReadAll(r.Body)
	fmt.Println(body)
	if err != nil {
		core.JSONError{
			Status:  core.Error,
			Message: err.Error(),
		}.Respond(w, http.StatusNoContent)
		return
	}
	var login LoginArgs
	err = json.Unmarshal(body, &login)
	if err != nil {
		core.JSONError{
			Status:  core.Error,
			Message: err.Error(),
		}.Respond(w, http.StatusNoContent)
		return
	}

	user, err := models.Verify(core.DB, context.Background(), login.Email, login.Password)
	if user == nil {
		core.JSONError{
			Status:  core.Error,
			Message: "User not found.",
		}.Respond(w, http.StatusNotFound)
		return
	}
	if err != nil {
		core.JSONError{
			Status:  core.Error,
			Message: err.Error(),
		}.Respond(w, http.StatusNoContent)
		return
	}

	claims := Claims{
		UserID: user.UserID.String(),
		RegisteredClaims: jwt.RegisteredClaims{
			Issuer:    "latosa-escrima.fr",
			Subject:   "authentification",
			ExpiresAt: jwt.NewNumericDate(time.Now().Add(time.Hour * 24)),
			IssuedAt:  jwt.NewNumericDate(time.Now()),
		},
	}

	token := jwt.NewWithClaims(jwt.SigningMethodHS256, claims)
	signed, err := token.SignedString(MySigningKey)
	if err != nil {
		core.JSONError{
			Status:  core.Error,
			Message: err.Error(),
		}.Respond(w, http.StatusNoContent)
		return
	}

	core.JSONSuccess{
		Status:  core.Success,
		Message: "JWT Created",
		Data:    signed,
	}.Respond(w, http.StatusCreated)
}
