backend-service/internal/server/server.go

206 lines
5.5 KiB
Go
Raw Normal View History

package server
import (
"fmt"
"log"
"attune-heart-therapy/internal/config"
"attune-heart-therapy/internal/database"
"attune-heart-therapy/internal/handlers"
"attune-heart-therapy/internal/services"
"github.com/gin-gonic/gin"
)
type Server struct {
config *config.Config
db *database.DB
router *gin.Engine
paymentHandler *handlers.PaymentHandler
bookingHandler *handlers.BookingHandler
adminHandler *handlers.AdminHandler
}
func New(cfg *config.Config) *Server {
// Set Gin mode based on environment
gin.SetMode(gin.ReleaseMode)
router := gin.New()
// Add basic middleware
router.Use(gin.Logger())
router.Use(gin.Recovery())
return &Server{
config: cfg,
router: router,
}
}
// Initialize sets up the database connection and runs migrations
func (s *Server) Initialize() error {
// Initialize database connection
db, err := database.New(s.config)
if err != nil {
return fmt.Errorf("failed to initialize database: %w", err)
}
s.db = db
// Run database migrations
if err := s.db.Migrate(); err != nil {
return fmt.Errorf("failed to run database migrations: %w", err)
}
// Seed database with initial data
if err := s.db.Seed(); err != nil {
return fmt.Errorf("failed to seed database: %w", err)
}
// Initialize services and handlers
s.initializeServices()
log.Println("Server initialization completed successfully")
return nil
}
func (s *Server) Start() error {
// Initialize database and run migrations
if err := s.Initialize(); err != nil {
return err
}
// Setup routes
s.setupRoutes()
// Start server
addr := fmt.Sprintf("%s:%s", s.config.Server.Host, s.config.Server.Port)
log.Printf("Starting server on %s", addr)
return s.router.Run(addr)
}
// Shutdown gracefully shuts down the server
func (s *Server) Shutdown() error {
if s.db != nil {
log.Println("Closing database connection...")
return s.db.Close()
}
return nil
}
func (s *Server) setupRoutes() {
// Health check endpoint
s.router.GET("/health", s.healthCheck)
// API v1 routes group
v1 := s.router.Group("/api")
{
// Auth routes (will be implemented in later tasks)
auth := v1.Group("/auth")
{
auth.POST("/register", func(c *gin.Context) {
c.JSON(501, gin.H{"message": "Not implemented yet"})
})
auth.POST("/login", func(c *gin.Context) {
c.JSON(501, gin.H{"message": "Not implemented yet"})
})
}
// Schedule routes - public endpoint for getting available slots
v1.GET("/schedules", s.bookingHandler.GetAvailableSlots)
// Booking routes - require authentication
bookings := v1.Group("/bookings")
// Note: Authentication middleware will be added in task 13
{
bookings.GET("/", s.bookingHandler.GetUserBookings)
bookings.POST("/", s.bookingHandler.CreateBooking)
bookings.PUT("/:id/cancel", s.bookingHandler.CancelBooking)
bookings.PUT("/:id/reschedule", s.bookingHandler.RescheduleBooking)
}
// Payment routes
payments := v1.Group("/payments")
{
payments.POST("/intent", s.paymentHandler.CreatePaymentIntent)
payments.POST("/confirm", s.paymentHandler.ConfirmPayment)
payments.POST("/webhook", s.paymentHandler.HandleWebhook)
}
// Admin routes - require admin authentication
admin := v1.Group("/admin")
// Note: Admin authentication middleware will be added in task 13
{
admin.GET("/dashboard", s.adminHandler.GetDashboard)
admin.POST("/schedules", s.adminHandler.CreateSchedule)
admin.PUT("/schedules/:id", s.adminHandler.UpdateSchedule)
admin.GET("/users", s.adminHandler.GetUsers)
admin.GET("/bookings", s.adminHandler.GetBookings)
admin.GET("/reports/financial", s.adminHandler.GetFinancialReports)
}
}
}
// initializeServices sets up all services and handlers
func (s *Server) initializeServices() {
// Initialize repositories
repos := s.db.GetRepositories()
// Initialize Jitsi service
jitsiService := services.NewJitsiService(&s.config.Jitsi)
// Initialize notification service
notificationService := services.NewNotificationService(repos.Notification, s.config)
// Initialize JWT service (needed for user service)
jwtService := services.NewJWTService(s.config.JWT.Secret, s.config.JWT.Expiration)
// Initialize user service with notification integration
_ = services.NewUserService(repos.User, jwtService, notificationService) // Ready for auth handlers
// Initialize payment service with notification integration
paymentService := services.NewPaymentService(s.config, repos.Booking, repos.User, notificationService)
// Initialize booking service with notification integration
bookingService := services.NewBookingService(
repos.Booking,
repos.Schedule,
repos.User,
jitsiService,
paymentService,
notificationService,
)
// Initialize admin service
adminService := services.NewAdminService(repos.User, repos.Booking, repos.Schedule)
// Initialize handlers
s.paymentHandler = handlers.NewPaymentHandler(paymentService)
s.bookingHandler = handlers.NewBookingHandler(bookingService)
s.adminHandler = handlers.NewAdminHandler(adminService)
}
// healthCheck handles the health check endpoint
func (s *Server) healthCheck(c *gin.Context) {
response := gin.H{
"status": "ok",
"message": "Video Conference Booking System API",
}
// Check database connectivity
if s.db != nil {
if err := s.db.Health(); err != nil {
response["status"] = "error"
response["database"] = "disconnected"
response["error"] = err.Error()
c.JSON(500, response)
return
}
response["database"] = "connected"
} else {
response["database"] = "not initialized"
}
c.JSON(200, response)
}