package handlers

import (
	"fmt"
	"net/http"

	"github.com/gin-gonic/gin"
	"go.uber.org/zap"
	"veza-backend-api/internal/services"
)

type ChatHandler struct {
	chatService *services.ChatService
	userService *services.UserService
	logger      *zap.Logger
}

func NewChatHandler(chatService *services.ChatService, userService *services.UserService, logger *zap.Logger) *ChatHandler {
	return &ChatHandler{
		chatService: chatService,
		userService: userService,
		logger:      logger,
	}
}

func (h *ChatHandler) GetToken(c *gin.Context) {
	userID := c.GetInt64("user_id")
	if userID == 0 {
		c.JSON(http.StatusUnauthorized, gin.H{"error": "unauthorized"})
		return
	}

	// Get username from DB
	user, err := h.userService.GetByID(userID)
	username := "user"
	if err == nil && user != nil {
		username = user.Username
	} else {
		// Fallback
		username = fmt.Sprintf("user_%d", userID)
	}

	token, err := h.chatService.GenerateToken(userID, username)
	if err != nil {
		h.logger.Error("Failed to generate chat token", zap.Error(err))
		c.JSON(http.StatusInternalServerError, gin.H{"error": "failed to generate token"})
		return
	}

	c.JSON(http.StatusOK, token)
}
