package handlers

import (
	"net/http"

	"veza-backend-api/internal/services"

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

// GetProfile handles profile retrieval
func GetProfile(userService *services.UserService) gin.HandlerFunc {
	return func(c *gin.Context) {
		userID, exists := c.Get("user_id")
		if !exists {
			c.JSON(http.StatusUnauthorized, gin.H{"error": "User not authenticated"})
			return
		}

		user, err := userService.GetByID(int64(userID.(int)))
		if err != nil {
			c.JSON(http.StatusNotFound, gin.H{"error": "User not found"})
			return
		}

		c.JSON(http.StatusOK, user)
	}
}

// GetProfileByUsername retrieves a public profile by username
func GetProfileByUsername(userService *services.UserService) gin.HandlerFunc {
	return func(c *gin.Context) {
		username := c.Param("username")

		user, err := userService.GetByUsername(username)
		if err != nil {
			c.JSON(http.StatusNotFound, gin.H{"error": "User not found"})
			return
		}

		// Only return public profile fields
		publicProfile := gin.H{
			"id":           user.ID,
			"username":     user.Username,
			"first_name":   user.FirstName,
			"last_name":    user.LastName,
			"avatar_url":   user.Avatar,
			"bio":          user.Bio,
			"location":     user.Location,
			"created_at":   user.CreatedAt,
		}

		c.JSON(http.StatusOK, gin.H{"profile": publicProfile})
	}
}

// UpdateProfile handles profile updates
func UpdateProfile(userService *services.UserService) gin.HandlerFunc {
	return func(c *gin.Context) {
		userID, exists := c.Get("user_id")
		if !exists {
			c.JSON(http.StatusUnauthorized, gin.H{"error": "User not authenticated"})
			return
		}

		var req services.UpdateProfileRequest
		if err := c.ShouldBindJSON(&req); err != nil {
			c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
			return
		}

		user, err := userService.UpdateProfileWithRequest(int64(userID.(int)), &req)
		if err != nil {
			c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
			return
		}

		c.JSON(http.StatusOK, user)
	}
}

// UploadAvatar handles avatar upload
func UploadAvatar(userService *services.UserService) gin.HandlerFunc {
	return func(c *gin.Context) {
		userID, exists := c.Get("user_id")
		if !exists {
			c.JSON(http.StatusUnauthorized, gin.H{"error": "User not authenticated"})
			return
		}

		file, err := c.FormFile("avatar")
		if err != nil {
			c.JSON(http.StatusBadRequest, gin.H{"error": "Missing avatar file"})
			return
		}

		// Validate file size (max 5MB)
		if file.Size > 5*1024*1024 {
			c.JSON(http.StatusBadRequest, gin.H{"error": "File too large (max 5MB)"})
			return
		}

		// Validate file type
		allowedTypes := []string{"image/jpeg", "image/png", "image/webp"}
		isValid := false
		for _, t := range allowedTypes {
			if file.Header.Get("Content-Type") == t {
				isValid = true
				break
			}
		}

		if !isValid {
			c.JSON(http.StatusBadRequest, gin.H{"error": "Invalid file type"})
			return
		}

		avatarURL, err := userService.UploadAvatar(int64(userID.(int)), file)
		if err != nil {
			c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
			return
		}

		c.JSON(http.StatusOK, gin.H{"avatar_url": avatarURL})
	}
}

// GetUserStats retrieves user statistics
func GetUserStats(userService *services.UserService) gin.HandlerFunc {
	return func(c *gin.Context) {
		username := c.Param("username")

		stats, err := userService.GetUserStats(username)
		if err != nil {
			c.JSON(http.StatusNotFound, gin.H{"error": "User not found"})
			return
		}

		c.JSON(http.StatusOK, stats)
	}
}
