package main

import (
	"log"
	"os"

	"github.com/gin-gonic/gin"
	"github.com/niangaodev/art-code/config"
	"github.com/niangaodev/art-code/handlers"
	"github.com/niangaodev/art-code/middleware"
	"github.com/niangaodev/art-code/repositories"
	"github.com/niangaodev/art-code/utils"
)

func main() {
	// 加载 .env 文件（必须在其他初始化之前）
	config.LoadEnvFile()

	// 初始化数据库连接
	config.InitDB()
	defer config.CloseDB()

	// 运行数据库迁移 (Convert Datetime to BigInt)
	// repositories.MigrateToBigInt() // 已禁用自动迁移
	repositories.MigratePostHistoryFields()
	repositories.MigratePostSnippets()
	repositories.MigratePostUserID()
	repositories.MigrateUserAvatar()
	repositories.MigrateUserProfileFields()
	repositories.MigrateVideoModule()
	repositories.MigratePptTemplates()

	// 初始化ip2region (如果文件不存在，将降级为普通IP记录)
	// 函数会自动从环境变量或可执行文件目录查找 ip2region.xdb
	utils.InitIP2Region("")

	// 创建Gin引擎
	router := gin.New()

	// 配置中间件
	router.Use(middleware.CorsMiddleware())
	router.Use(middleware.AccessLogMiddleware()) // 添加访问日志中间件
	router.Use(gin.Recovery())

	// 静态文件服务 - 用于访问上传的本地文件
	// 从环境变量读取配置，如果未设置则使用默认值
	uploadsBaseURL := os.Getenv("UPLOADS_BASE_URL")
	if uploadsBaseURL == "" {
		uploadsBaseURL = "/uploads"
	}
	uploadsBasePath := os.Getenv("UPLOADS_BASE_PATH")
	if uploadsBasePath == "" {
		uploadsBasePath = "./uploads"
	}
	router.Static(uploadsBaseURL, uploadsBasePath)

	// API路由组
	api := router.Group("/api")
	{
		// 作品路由
		api.GET("/works", handlers.GetWorks)
		api.GET("/works/:id", handlers.GetWorkByID)

		// 视频路由
		api.GET("/video-categories", handlers.GetVideoCategories)
		api.GET("/video-albums", handlers.GetVideoAlbums)
		api.GET("/video-albums/:id", handlers.GetVideoAlbumByID)
		api.GET("/video-albums/:id/videos", handlers.GetAlbumVideos)
		api.GET("/videos", handlers.GetVideos)
		api.GET("/videos/:id", handlers.GetVideoByID)

		// 博客路由
		api.GET("/posts", handlers.GetPosts)
		api.GET("/posts/:id", handlers.GetPost)
		api.GET("/search/hot", handlers.GetHotSearches)
		api.GET("/posts/:id/recommendations", handlers.GetRecommendedPosts)

		// 分类路由
		api.GET("/categories", handlers.GetCategories)
		api.GET("/categories/:id", handlers.GetCategoryByID)

		// 专栏路由
		api.GET("/columns", handlers.GetColumns)
		api.GET("/columns/:id", handlers.GetColumnByID)
		api.GET("/columns/:id/posts", handlers.GetColumnPosts)
		api.GET("/columns/:id/post-titles", handlers.GetColumnPostTitles)

		// 代码片段路由
		api.GET("/snippets", handlers.GetSnippets)
		api.GET("/snippets/:id", handlers.GetSnippet)
		api.GET("/code-types", handlers.GetCodeTypes)

		// 标签路由
		api.GET("/tags", handlers.GetTags)
		api.GET("/tags/:id", handlers.GetTag)
		api.GET("/tags/:id/posts", handlers.GetPostsByTagID)

		// 公开设置路由
		api.GET("/settings", handlers.GetSettings)

		// 代码执行路由
		api.POST("/run", handlers.RunCode)
		api.GET("/proxy", handlers.ProxyRequest)

		// 关于页面路由
		api.GET("/about", handlers.GetAboutProfile)

		// 合作页面路由
		api.GET("/testimonials", handlers.GetTestimonials)
		api.GET("/partners", handlers.GetPartners)

		// PPT 模板
		api.GET("/ppt-templates", handlers.GetPptTemplates)
		api.GET("/ppt-templates/default", handlers.GetDefaultPptTemplate)

		// 咨询相关路由
		api.POST("/inquiries", handlers.SubmitInquiry)
		api.GET("/email-suffixes", handlers.GetEmailSuffixes)

		// 用户公开资料
		api.GET("/users/:id/profile", handlers.GetUserProfile)
		api.GET("/users/:id/posts", handlers.GetUserPosts)
	}

	// 管理员API路由组
	admin := router.Group("/api/admin")
	{
		// 登录路由（不需要认证）
		admin.POST("/login", handlers.Login)

		// 需要认证的路由
		authAdmin := admin.Group("/")
		authAdmin.Use(middleware.AuthMiddleware(), middleware.OperationLogMiddleware())
		{
			// 当前用户
			authAdmin.GET("/me", handlers.GetCurrentUser)
			authAdmin.PUT("/me", handlers.UpdateCurrentUser)
			authAdmin.PUT("/me/password", handlers.UpdateCurrentUserPassword)

			// 用户管理
			authAdmin.GET("/users", middleware.PermissionMiddleware("users", "read"), handlers.AdminGetUsers)
			authAdmin.GET("/users/:id", middleware.PermissionMiddleware("users", "read"), handlers.AdminGetUser)
			authAdmin.POST("/users", middleware.PermissionMiddleware("users", "create"), handlers.AdminCreateUser)
			authAdmin.PUT("/users/:id", middleware.PermissionMiddleware("users", "update"), handlers.AdminUpdateUser)
			authAdmin.DELETE("/users/:id", middleware.PermissionMiddleware("users", "delete"), handlers.AdminDeleteUser)

			// 角色管理
			authAdmin.GET("/roles", middleware.PermissionMiddleware("roles", "read"), handlers.AdminGetRoles)
			authAdmin.POST("/roles", middleware.PermissionMiddleware("roles", "create"), handlers.AdminCreateRole)
			authAdmin.PUT("/roles/:id", middleware.PermissionMiddleware("roles", "update"), handlers.AdminUpdateRole)
			authAdmin.DELETE("/roles/:id", middleware.PermissionMiddleware("roles", "delete"), handlers.AdminDeleteRole)

			// 权限管理
			authAdmin.GET("/permissions", middleware.PermissionMiddleware("roles", "read"), handlers.AdminGetPermissions)
			authAdmin.PUT("/roles/:id/permissions", middleware.PermissionMiddleware("roles", "update"), handlers.AdminUpdateRolePermissions)

			// 作品管理
			authAdmin.GET("/works", middleware.PermissionMiddleware("works", "read"), handlers.AdminGetWorks)
			authAdmin.POST("/works", middleware.PermissionMiddleware("works", "create"), handlers.AdminCreateWork)
			authAdmin.PUT("/works/:id", middleware.PermissionMiddleware("works", "update"), handlers.AdminUpdateWork)
			authAdmin.DELETE("/works/:id", middleware.PermissionMiddleware("works", "delete"), handlers.AdminDeleteWork)

			// 视频管理
			authAdmin.GET("/video-categories", middleware.PermissionMiddleware("videos", "read"), handlers.AdminGetVideoCategories)
			authAdmin.POST("/video-categories", middleware.PermissionMiddleware("videos", "create"), handlers.AdminCreateVideoCategory)
			authAdmin.PUT("/video-categories/:id", middleware.PermissionMiddleware("videos", "update"), handlers.AdminUpdateVideoCategory)
			authAdmin.DELETE("/video-categories/:id", middleware.PermissionMiddleware("videos", "delete"), handlers.AdminDeleteVideoCategory)

			authAdmin.GET("/video-albums", middleware.PermissionMiddleware("videos", "read"), handlers.AdminGetVideoAlbums)
			authAdmin.POST("/video-albums", middleware.PermissionMiddleware("videos", "create"), handlers.AdminCreateVideoAlbum)
			authAdmin.PUT("/video-albums/:id", middleware.PermissionMiddleware("videos", "update"), handlers.AdminUpdateVideoAlbum)
			authAdmin.DELETE("/video-albums/:id", middleware.PermissionMiddleware("videos", "delete"), handlers.AdminDeleteVideoAlbum)
			authAdmin.GET("/video-albums/:id/video-ids", middleware.PermissionMiddleware("videos", "read"), handlers.AdminGetAlbumVideoIDs)
			authAdmin.POST("/video-albums/:id/videos", middleware.PermissionMiddleware("videos", "update"), handlers.AdminAddVideoToAlbum)
			authAdmin.DELETE("/video-albums/:id/videos/:videoId", middleware.PermissionMiddleware("videos", "update"), handlers.AdminRemoveVideoFromAlbum)

			authAdmin.GET("/videos", middleware.PermissionMiddleware("videos", "read"), handlers.AdminGetVideos)
			authAdmin.GET("/videos/:id", middleware.PermissionMiddleware("videos", "read"), handlers.AdminGetVideoByID)
			authAdmin.POST("/videos", middleware.PermissionMiddleware("videos", "create"), handlers.AdminCreateVideo)
			authAdmin.PUT("/videos/:id", middleware.PermissionMiddleware("videos", "update"), handlers.AdminUpdateVideo)
			authAdmin.DELETE("/videos/:id", middleware.PermissionMiddleware("videos", "delete"), handlers.AdminDeleteVideo)

			// 代码片段管理
			authAdmin.GET("/snippets", middleware.PermissionMiddleware("snippets", "read"), handlers.AdminGetSnippets)
			authAdmin.POST("/snippets", middleware.PermissionMiddleware("snippets", "create"), handlers.AdminCreateSnippet)
			authAdmin.PUT("/snippets/:id", middleware.PermissionMiddleware("snippets", "update"), handlers.AdminUpdateSnippet)
			authAdmin.DELETE("/snippets/:id", middleware.PermissionMiddleware("snippets", "delete"), handlers.AdminDeleteSnippet)

			// 代码类型管理
			authAdmin.GET("/code-types", middleware.PermissionMiddleware("snippets", "read"), handlers.AdminGetCodeTypes)
			authAdmin.POST("/code-types", middleware.PermissionMiddleware("snippets", "create"), handlers.AdminCreateCodeType)
			authAdmin.PUT("/code-types/:id", middleware.PermissionMiddleware("snippets", "update"), handlers.AdminUpdateCodeType)
			authAdmin.DELETE("/code-types/:id", middleware.PermissionMiddleware("snippets", "delete"), handlers.AdminDeleteCodeType)

			// 系统配置管理
			authAdmin.GET("/settings", middleware.PermissionMiddleware("settings", "read"), handlers.AdminGetSettings)
			authAdmin.POST("/settings", middleware.PermissionMiddleware("settings", "create"), handlers.AdminCreateSetting)
			authAdmin.PUT("/settings", middleware.PermissionMiddleware("settings", "update"), handlers.AdminUpdateSettings)
			authAdmin.PUT("/settings/:id", middleware.PermissionMiddleware("settings", "update"), handlers.AdminUpdateSetting)
			authAdmin.DELETE("/settings/:key", middleware.PermissionMiddleware("settings", "delete"), handlers.AdminDeleteSetting)

			// 仪表盘统计
			authAdmin.GET("/dashboard/stats", middleware.PermissionMiddleware("dashboard", "read"), handlers.GetDashboardStats)

			// 文章管理
			authAdmin.GET("/posts", middleware.PermissionMiddleware("posts", "read"), handlers.AdminGetPosts)
			authAdmin.POST("/posts", middleware.PermissionMiddleware("posts", "create"), handlers.AdminCreatePost)
			authAdmin.PUT("/posts/:id", middleware.PermissionMiddleware("posts", "update"), handlers.AdminUpdatePost)
			authAdmin.PATCH("/posts/:id/relations", middleware.PermissionMiddleware("posts", "update"), handlers.AdminUpdatePostRelations) // 更新文章关联关系
			authAdmin.PATCH("/posts/:id/status", middleware.PermissionMiddleware("posts", "update"), handlers.AdminTogglePostStatus)       // 新增状态切换
			authAdmin.DELETE("/posts/:id", middleware.PermissionMiddleware("posts", "delete"), handlers.AdminDeletePost)

			// 分类管理 (复用 posts 权限)
			authAdmin.GET("/categories", middleware.PermissionMiddleware("posts", "read"), handlers.GetCategories) // Admin also uses public handler or specific if needed
			authAdmin.POST("/categories", middleware.PermissionMiddleware("posts", "create"), handlers.AdminCreateCategory)
			authAdmin.PUT("/categories/:id", middleware.PermissionMiddleware("posts", "update"), handlers.AdminUpdateCategory)
			authAdmin.DELETE("/categories/:id", middleware.PermissionMiddleware("posts", "delete"), handlers.AdminDeleteCategory)

			// 专栏管理 (复用 posts 权限)
			authAdmin.GET("/columns", middleware.PermissionMiddleware("posts", "read"), handlers.GetColumns)
			authAdmin.POST("/columns", middleware.PermissionMiddleware("posts", "create"), handlers.AdminCreateColumn)
			authAdmin.PUT("/columns/:id", middleware.PermissionMiddleware("posts", "update"), handlers.AdminUpdateColumn)
			authAdmin.DELETE("/columns/:id", middleware.PermissionMiddleware("posts", "delete"), handlers.AdminDeleteColumn)
			authAdmin.POST("/columns/:id/posts", middleware.PermissionMiddleware("posts", "update"), handlers.AdminAddPostToColumn)
			authAdmin.DELETE("/columns/:id/posts/:postId", middleware.PermissionMiddleware("posts", "update"), handlers.AdminRemovePostFromColumn)

			// 文章历史记录
			authAdmin.GET("/posts/:id/history", middleware.PermissionMiddleware("posts", "read"), handlers.AdminGetPostHistory)
			authAdmin.GET("/posts/:id/history/diff", middleware.PermissionMiddleware("posts", "read"), handlers.AdminGetPostHistoryDiff)
			authAdmin.POST("/posts/:id/history/:version/restore", middleware.PermissionMiddleware("posts", "update"), handlers.AdminRestorePostHistory)
			authAdmin.GET("/posts/:id/history/:version", middleware.PermissionMiddleware("posts", "read"), handlers.AdminGetPostHistoryByVersion)

			// 操作日志管理
			authAdmin.GET("/operation-logs", middleware.PermissionMiddleware("operation_logs", "read"), handlers.AdminGetOperationLogs)

			// 访问日志管理
			authAdmin.GET("/access-logs", middleware.PermissionMiddleware("operation_logs", "read"), handlers.AdminGetAccessLogs)
			authAdmin.GET("/posts/:id/access-logs", middleware.PermissionMiddleware("posts", "read"), handlers.AdminGetPostAccessLogs)

			// 仪表盘数据
			authAdmin.GET("/dashboard/activities", middleware.PermissionMiddleware("dashboard", "read"), handlers.AdminGetRecentActivities)

			// 标签管理
			authAdmin.GET("/tags", middleware.PermissionMiddleware("tags", "read"), handlers.AdminGetTags)
			authAdmin.GET("/tags/:id", middleware.PermissionMiddleware("tags", "read"), handlers.GetTag)
			authAdmin.POST("/tags", middleware.PermissionMiddleware("tags", "create"), handlers.AdminCreateTag)
			authAdmin.PUT("/tags/:id", middleware.PermissionMiddleware("tags", "update"), handlers.AdminUpdateTag)
			authAdmin.DELETE("/tags/:id", middleware.PermissionMiddleware("tags", "delete"), handlers.AdminDeleteTag)

			// 关于页面管理 (复用 settings 权限)
			authAdmin.GET("/about", middleware.PermissionMiddleware("settings", "read"), handlers.AdminGetAboutProfiles)
			authAdmin.POST("/about", middleware.PermissionMiddleware("settings", "create"), handlers.AdminCreateAboutProfile)
			authAdmin.PUT("/about/:id", middleware.PermissionMiddleware("settings", "update"), handlers.AdminUpdateAboutProfile)
			authAdmin.DELETE("/about/:id", middleware.PermissionMiddleware("settings", "delete"), handlers.AdminDeleteAboutProfile)

			// 客户评价管理 (复用 settings 权限)
			authAdmin.POST("/testimonials", middleware.PermissionMiddleware("settings", "create"), handlers.AdminCreateTestimonial)
			authAdmin.PUT("/testimonials/:id", middleware.PermissionMiddleware("settings", "update"), handlers.AdminUpdateTestimonial)
			authAdmin.DELETE("/testimonials/:id", middleware.PermissionMiddleware("settings", "delete"), handlers.AdminDeleteTestimonial)

			// 合作伙伴管理 (复用 settings 权限)
			authAdmin.POST("/partners", middleware.PermissionMiddleware("settings", "create"), handlers.AdminCreatePartner)
			authAdmin.PUT("/partners/:id", middleware.PermissionMiddleware("settings", "update"), handlers.AdminUpdatePartner)
			authAdmin.DELETE("/partners/:id", middleware.PermissionMiddleware("settings", "delete"), handlers.AdminDeletePartner)

			// PPT 模板管理 (复用 settings 权限)
			authAdmin.GET("/ppt-templates", middleware.PermissionMiddleware("settings", "read"), handlers.AdminGetPptTemplates)
			authAdmin.POST("/ppt-templates", middleware.PermissionMiddleware("settings", "create"), handlers.AdminCreatePptTemplate)
			authAdmin.PUT("/ppt-templates/:id", middleware.PermissionMiddleware("settings", "update"), handlers.AdminUpdatePptTemplate)
			authAdmin.DELETE("/ppt-templates/:id", middleware.PermissionMiddleware("settings", "delete"), handlers.AdminDeletePptTemplate)

			// 咨询管理
			authAdmin.GET("/inquiries", middleware.PermissionMiddleware("settings", "read"), handlers.AdminGetInquiries)
			authAdmin.PUT("/inquiries/:id/status", middleware.PermissionMiddleware("settings", "update"), handlers.AdminUpdateInquiryStatus)

			// 邮箱后缀配置
			authAdmin.GET("/email-suffixes", middleware.PermissionMiddleware("settings", "read"), handlers.AdminGetEmailSuffixes)
			authAdmin.POST("/email-suffixes", middleware.PermissionMiddleware("settings", "create"), handlers.AdminCreateEmailSuffix)
			authAdmin.PUT("/email-suffixes/:id", middleware.PermissionMiddleware("settings", "update"), handlers.AdminUpdateEmailSuffix)
			authAdmin.DELETE("/email-suffixes/:id", middleware.PermissionMiddleware("settings", "delete"), handlers.AdminDeleteEmailSuffix)

			// 搜索记录管理 (复用 settings 权限)
			authAdmin.GET("/search-logs", middleware.PermissionMiddleware("settings", "read"), handlers.AdminGetSearchLogs)
			authAdmin.DELETE("/search-logs/:id", middleware.PermissionMiddleware("settings", "delete"), handlers.AdminDeleteSearchLog)

			// 附件管理 (复用 settings 权限)
			authAdmin.POST("/attachments/upload", middleware.PermissionMiddleware("settings", "create"), handlers.AdminUploadAttachment)
			authAdmin.GET("/attachments", middleware.PermissionMiddleware("settings", "read"), handlers.AdminGetAttachments)
			authAdmin.PUT("/attachments/:id", middleware.PermissionMiddleware("settings", "update"), handlers.AdminUpdateAttachment)
			authAdmin.DELETE("/attachments/:id", middleware.PermissionMiddleware("settings", "delete"), handlers.AdminDeleteAttachment)

			// 附件分类管理
			authAdmin.GET("/attachment-categories", middleware.PermissionMiddleware("settings", "read"), handlers.AdminGetAttachmentCategories)
			authAdmin.POST("/attachment-categories", middleware.PermissionMiddleware("settings", "create"), handlers.AdminCreateAttachmentCategory)
			authAdmin.PUT("/attachment-categories/:id", middleware.PermissionMiddleware("settings", "update"), handlers.AdminUpdateAttachmentCategory)
			authAdmin.DELETE("/attachment-categories/:id", middleware.PermissionMiddleware("settings", "delete"), handlers.AdminDeleteAttachmentCategory)

			// OSS配置管理
			authAdmin.GET("/oss-configs", middleware.PermissionMiddleware("settings", "read"), handlers.AdminGetOSSConfigs)
			authAdmin.POST("/oss-configs", middleware.PermissionMiddleware("settings", "create"), handlers.AdminCreateOSSConfig)
			authAdmin.PUT("/oss-configs/:id", middleware.PermissionMiddleware("settings", "update"), handlers.AdminUpdateOSSConfig)
			authAdmin.DELETE("/oss-configs/:id", middleware.PermissionMiddleware("settings", "delete"), handlers.AdminDeleteOSSConfig)
		}
	}

	// 启动服务器
	log.Println("Server running on http://localhost:18081")
	if err := router.Run(":8081"); err != nil {
		log.Fatalf("Failed to start server: %v", err)
	}
}
