package handlers

import (
	"net/http"

	"git.linuxforward.com/byop/byop-engine/auth"
	"git.linuxforward.com/byop/byop-engine/dbstore"
	"github.com/gin-gonic/gin"
	"golang.org/x/crypto/bcrypt"
)

// AuthHandler handles authentication-related operations
type AuthHandler struct {
	authService auth.Service
	userStore   *dbstore.UserStore
}

// NewAuthHandler creates a new AuthHandler
func NewAuthHandler(authService auth.Service, userStore *dbstore.UserStore) *AuthHandler {
	return &AuthHandler{
		authService: authService,
		userStore:   userStore,
	}
}

// Login handles user authentication
func (h *AuthHandler) Login(c *gin.Context) {
	var credentials struct {
		Email    string `json:"email"`
		Password string `json:"password"`
	}

	if err := c.ShouldBindJSON(&credentials); err != nil {
		c.JSON(http.StatusBadRequest, gin.H{"error": "Invalid request body"})
		return
	}

	// Validate user credentials
	user, err := h.userStore.GetUserByEmail(credentials.Email)
	if err != nil {
		c.JSON(http.StatusInternalServerError, gin.H{"error": "Failed to fetch user"})
		return
	}

	if user == nil {
		c.JSON(http.StatusUnauthorized, gin.H{"error": "Invalid email"})
		return
	}

	// Check password using bcrypt
	if err := bcrypt.CompareHashAndPassword([]byte(user.Password), []byte(credentials.Password)); err != nil {
		c.JSON(http.StatusUnauthorized, gin.H{"error": "Invalid password"})
		return
	}

	// TODO: Implement authentication logic
	resp, err := h.authService.GenerateToken(c, credentials.Email, "owner")
	if err != nil {
		c.JSON(http.StatusInternalServerError, gin.H{"error": "Failed to generate token"})
		return
	}

	c.JSON(http.StatusOK, resp)
}

// RefreshToken handles token refresh
func (h *AuthHandler) RefreshToken(c *gin.Context) {
	// TODO: Implement token refresh logic

	resp := gin.H{
		"token": "new-dummy-token",
	}

	c.JSON(http.StatusOK, resp)
}

// Logout handles user logout
func (h *AuthHandler) Logout(c *gin.Context) {
	// TODO: Implement logout logic

	c.Status(http.StatusNoContent)
}
