package handlers

import (
	"fmt"
	"github.com/google/uuid"
	"net/http"

	"github.com/gin-gonic/gin"
	"go.uber.org/zap"
	apperrors "veza-backend-api/internal/errors"
	"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,
	}
}

// GetToken generates a JWT token for the chat service
// @Summary      Get Chat Token
// @Description  Generate a short-lived token for chat authentication
// @Tags         Chat
// @Accept       json
// @Produce      json
// @Security     BearerAuth
// @Success      200  {object}  APIResponse{data=object{token=string}}
// @Failure      401  {object}  APIResponse "Unauthorized"
// @Failure      500  {object}  APIResponse "Internal Error"
// @Router       /chat/token [get]
func (h *ChatHandler) GetToken(c *gin.Context) {
	userIDVal, exists := c.Get("user_id")
	if !exists {
		c.JSON(http.StatusUnauthorized, gin.H{"error": "unauthorized"})
		return
	}
	userID, ok := userIDVal.(uuid.UUID)
	if !ok || userID == uuid.Nil {
		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_%s", 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
	}

	RespondSuccess(c, http.StatusOK, token)
}

// GetStats returns chat statistics
// BE-API-006: Implement chat stats endpoint
func (h *ChatHandler) GetStats(c *gin.Context) {
	stats, err := h.chatService.GetStats(c.Request.Context())
	if err != nil {
		h.logger.Error("Failed to get chat stats", zap.Error(err))
		RespondWithAppError(c, apperrors.Wrap(apperrors.ErrCodeInternal, "Failed to get chat stats", err))
		return
	}

	RespondSuccess(c, http.StatusOK, stats)
}
