package main

import (
	"log"
	"project-dashboard/api"
	"project-dashboard/middleware"
	"project-dashboard/models"

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

func main() {
	// Initialize database
	models.InitDB()
	defer models.CloseDB()

	// Create default admin user if not exists
	createDefaultAdmin()

	// Set Gin mode
	gin.SetMode(gin.ReleaseMode)

	// Create Gin router
	r := gin.Default()

	// Configure CORS
	config := cors.DefaultConfig()
	config.AllowOrigins = []string{"http://localhost:3000", "http://localhost:3001"}
	config.AllowMethods = []string{"GET", "POST", "PUT", "DELETE", "OPTIONS"}
	config.AllowHeaders = []string{"Origin", "Content-Type", "Accept", "Authorization", "X-Requested-With"}
	config.AllowCredentials = true
	r.Use(cors.New(config))

	// Serve static files
	r.Static("/uploads", "./uploads")

	// Health check endpoint
	r.GET("/health", func(c *gin.Context) {
		c.JSON(200, gin.H{
			"status":  "ok",
			"message": "Project Dashboard API is running",
		})
	})

	// API routes
	v1 := r.Group("/api/v1")
	{
		// Authentication routes
		auth := v1.Group("/auth")
		{
			auth.POST("/register", api.Register)
			auth.POST("/login", api.Login)
			auth.GET("/profile", middleware.AuthMiddleware(), api.GetProfile)
			auth.PUT("/profile", middleware.AuthMiddleware(), api.UpdateProfile)
			auth.PUT("/change-password", middleware.AuthMiddleware(), api.ChangePassword)
		}

		// Project routes
		projects := v1.Group("/projects")
		projects.Use(middleware.AuthMiddleware())
		{
			projects.POST("", api.CreateProject)
			projects.GET("", api.GetProjects)

			// Project-specific routes
			project := projects.Group("/:project_id")
			project.Use(middleware.ProjectAccessMiddleware())
			{
				project.GET("", api.GetProject)
				project.PUT("", api.UpdateProject)
				project.DELETE("", api.DeleteProject)

				// Project members
				project.POST("/members", api.AddMember)
				project.DELETE("/members/:user_id", api.RemoveMember)

				// Tasks
				project.POST("/tasks", api.CreateTask)
				project.GET("/tasks", api.GetTasks)

				task := project.Group("/tasks/:task_id")
				{
					task.GET("", api.GetTask)
					task.PUT("", api.UpdateTask)
					task.DELETE("", api.DeleteTask)

					// Task comments
					task.POST("/comments", api.AddComment)

					// Task subtasks
					task.POST("/subtasks", api.CreateSubtask)
				}

				// Files
				project.POST("/files", api.UploadFile)
				project.GET("/files", api.GetFiles)

				file := project.Group("/files/:file_id")
				{
					file.GET("", api.DownloadFile)
					file.DELETE("", api.DeleteFile)
				}
			}
		}
	}

	// Start server
	log.Println("Starting server on :8080")
	if err := r.Run(":8080"); err != nil {
		log.Fatal("Failed to start server:", err)
	}
}

func createDefaultAdmin() {
	var admin models.User
	if err := models.GetDB().Where("email = ?", "admin@example.com").First(&admin).Error; err != nil {
		// Create default admin user
		admin = models.User{
			Email:     "admin@example.com",
			FirstName: "Admin",
			LastName:  "User",
			Role:      "admin",
		}

		if err := admin.HashPassword("admin123"); err != nil {
			log.Printf("Failed to hash admin password: %v", err)
			return
		}

		if err := models.GetDB().Create(&admin).Error; err != nil {
			log.Printf("Failed to create admin user: %v", err)
			return
		}

		log.Println("Default admin user created: admin@example.com / admin123")
	}
}
