package auth

import (
	"cargo-erp-backend/internal/handlers/dto"
	"cargo-erp-backend/internal/middleware"
	"cargo-erp-backend/internal/usecases"
	"cargo-erp-backend/pkg/helpers"
	"cargo-erp-backend/pkg/response"
	"context"
	"fmt"
	"net/http"
	"strconv"

	"github.com/gin-gonic/gin"
)

type AuthHandlerInterface interface {
	Router()
}
type AuthHandler struct {
	Helper helpers.HelperInterface
	Engine *gin.Engine
}

func NewAuthHandler(helper helpers.HelperInterface, e *gin.Engine) AuthHandlerInterface {
	return &AuthHandler{
		Helper: helper,
		Engine: e,
	}
}
func (h *AuthHandler) Router() {
	h.Engine.POST("login", h.Login)
	h.Engine.POST("logout", middleware.NewAuthMiddleware(h.Helper).Check(), h.Logout)
}
func (h *AuthHandler) Login(c *gin.Context) {
	u := usecases.NewAuthUsecase(h.Helper)
	var parameter dto.AuthRequest
	if err := c.BindJSON(&parameter); err != nil {
		response.Error(c, http.StatusBadRequest, err.Error())
		return
	}
	token, err := u.Login(parameter.Email, parameter.Password)
	if err != nil {
		response.Error(c, http.StatusUnauthorized, err.Error())
		return
	}
	cookieName := fmt.Sprintf("%v", h.Helper.Config().Get("cookie.name"))
	exp_time := fmt.Sprintf("%v", h.Helper.Config().Get("cookie.expiry_time"))
	t, _ := strconv.Atoi(exp_time)
	c.SetCookie(
		cookieName, // name
		token,      // value
		t,          // max age: 30 menit
		"/",        // path
		"",         // domain
		false,      // secure
		true,       // httpOnly
	)

	response.Success(c, dto.AuthResponse{
		Token: token,
	})
}
func (h *AuthHandler) Logout(c *gin.Context) {
	auth_key := c.MustGet("auth_key")
	ctx := context.Background()
	h.Helper.GetRedis("master").Del(ctx, fmt.Sprintf("%v", auth_key))
	cookieName := fmt.Sprintf("%v", h.Helper.Config().Get("cookie.name"))
	c.SetCookie(
		cookieName, // name
		"",         // value
		-3600,      // max age: 30 menit
		"/",        // path
		"",         // domain
		false,      // secure
		true,       // httpOnly
	)
	response.Success(c, map[string]interface{}{"message": "You are logged out"})
}
