package handlers

import (
	"net/http"

	"github.com/breakpilot/school-service/internal/services"
	"github.com/gin-gonic/gin"
	"github.com/jackc/pgx/v5/pgxpool"
)

// Handler holds all the service dependencies
type Handler struct {
	classService       *services.ClassService
	examService        *services.ExamService
	gradeService       *services.GradeService
	gradebookService   *services.GradebookService
	certificateService *services.CertificateService
	aiService          *services.AIService
}

// NewHandler creates a new Handler with all services
func NewHandler(db *pgxpool.Pool, llmGatewayURL string) *Handler {
	classService := services.NewClassService(db)
	examService := services.NewExamService(db)
	gradeService := services.NewGradeService(db)
	gradebookService := services.NewGradebookService(db)
	certificateService := services.NewCertificateService(db, gradeService, gradebookService)
	aiService := services.NewAIService(llmGatewayURL)

	return &Handler{
		classService:       classService,
		examService:        examService,
		gradeService:       gradeService,
		gradebookService:   gradebookService,
		certificateService: certificateService,
		aiService:          aiService,
	}
}

// Health returns the service health status
func (h *Handler) Health(c *gin.Context) {
	c.JSON(http.StatusOK, gin.H{
		"status":  "healthy",
		"service": "school-service",
	})
}

// getUserID extracts the user ID from the context (set by auth middleware)
func getUserID(c *gin.Context) string {
	return c.GetString("user_id")
}

// respondError sends an error response
func respondError(c *gin.Context, status int, message string) {
	c.JSON(status, gin.H{"error": message})
}

// respondSuccess sends a success response with data
func respondSuccess(c *gin.Context, data interface{}) {
	c.JSON(http.StatusOK, data)
}

// respondCreated sends a created response with data
func respondCreated(c *gin.Context, data interface{}) {
	c.JSON(http.StatusCreated, data)
}
