package handlers

import (
	"context"
	"encoding/json"
	"net/http"
	"portfolio/api/service/bcrypt"
	"portfolio/api/service/jwt"
	"portfolio/api/types"
	"portfolio/database/query"
	"time"
)

func Login(w http.ResponseWriter, r *http.Request) {
	var u *types.LoginUser

	if r.Header.Get("HX-Request") == "true" {
		u = handleHtmxLogin(r)
	} else {
		u = handleHttpLogin(w, r, u)
	}

	if u == nil {
		return
	}

	User, err := query.GetLogin(context.Background(), u)
	if err != nil {
		UnprocessableEntityHandler(w, err)
		return
	}

	if !bcrypt.CheckPasswordHash(u.Password, User.Password) {
		UnauthorizedHandler(w)
		return
	}

	jwtToken := jwt.CreateUserJWT(User.Name, User.ID, string(User.Role))

	cookie := &http.Cookie{
		Name:     "jwt",
		Value:    jwtToken,
		HttpOnly: true,
		Secure:   true,
		SameSite: http.SameSiteLaxMode,
		Expires:  time.Now().Add(24 * time.Hour),
	}

	http.SetCookie(w, cookie)

	w.WriteHeader(http.StatusOK)
	_, err = w.Write([]byte("login success"))
}

func handleHtmxLogin(r *http.Request) *types.LoginUser {
	return &types.LoginUser{
		Email:    r.PostFormValue("email"),
		Password: r.PostFormValue("password"),
	}
}

func handleHttpLogin(w http.ResponseWriter, r *http.Request, u *types.LoginUser) *types.LoginUser {
	if err := json.NewDecoder(r.Body).Decode(&u); err != nil {
		InternalServerErrorHandler(w, err)
		return nil
	}
	return u
}

func CanEdit(w http.ResponseWriter, r *http.Request) {

	_, audience, err := jwt.VerifyUser(r)
	if err != nil {
		w.WriteHeader(http.StatusOK)
		w.Write([]byte(""))
	}
	if audience == "owner" || audience == "admin" {
		w.WriteHeader(http.StatusOK)
		w.Write([]byte("<button class=\"button is-link\">Edit</button>"))
	} else {
		w.WriteHeader(http.StatusOK)
		w.Write([]byte(""))
	}
}
