package router

import (
	"mini-chat/internal/alert"
	"mini-chat/internal/api/admin"
	"mini-chat/internal/api/app"
	"mini-chat/internal/api/keyword"
	"mini-chat/internal/api/message"
	"mini-chat/internal/api/upload"
	"mini-chat/internal/api/wechat"
	"mini-chat/internal/cron"
	"mini-chat/internal/dblogger"
	"mini-chat/internal/pkg/core"
	"mini-chat/internal/pkg/logger"
	"mini-chat/internal/pkg/startup"
	"mini-chat/internal/repository/mysql"
	"mini-chat/internal/router/interceptor"

	"github.com/pkg/errors"
)

func NewHTTPMux(logger logger.CustomLogger, db mysql.Repo, cron cron.Server) (core.Mux, error) {
	if logger == nil {
		return nil, errors.New("logger required")
	}

	if db == nil {
		return nil, errors.New("db required")
	}

	mux, err := core.New(logger,
		core.WithEnableCors(),
		core.WithEnableSwagger(),
		core.WithEnablePProf(),
		core.WithAlertNotify(alert.NotifyHandler()),
		core.WithRequestLogger(dblogger.LoggerHandler(db)),
	)

	if err != nil {
		panic(err)
	}

	// 实例化拦截器
	interceptorHandler := interceptor.New(logger, db)

	adminHandler := admin.New(logger, db)
	appHandler := app.New(logger, db)
	uploadHandler := upload.New(logger, db)
	keywordHandler := keyword.New(logger, db)
	messageHandler := message.New(logger, db)
	wechatHandler := wechat.New(logger, db)

	// 管理端非认证接口路由组
	adminNonAuthApiRouter := mux.Group("/api/admin")
	{
		adminNonAuthApiRouter.GET("/license/status", func(ctx core.Context) {
			ctx.Payload(startup.Info())
		})

		adminNonAuthApiRouter.POST("/login", adminHandler.Login())               // 登录
		adminNonAuthApiRouter.POST("/upload/image", uploadHandler.UploadImage()) // 上传图片
	}

	appNonAuthApiRouter := mux.Group("/api/app")
	{
		appNonAuthApiRouter.POST("/user/create", appHandler.CreateAppUser())        // 新增小程序用户
		appNonAuthApiRouter.GET("/messages", messageHandler.AppMessagePageList())   // 消息列表
		appNonAuthApiRouter.POST("/send_message", messageHandler.UserSendMessage()) // 发送消息
	}

	// 微信 API 路由组
	wechatApiRouter := mux.Group("/api/wechat")
	{
		wechatApiRouter.POST("/qrcode", wechatHandler.GenerateQRCode())              // 生成微信小程序二维码（返回 Base64）
		wechatApiRouter.POST("/miniprogram/login", wechatHandler.MiniprogramLogin()) // 小程序登录
	}

	// 管理端认证接口路由组
	adminAuthApiRouter := mux.Group("/api/admin", core.WrapAuthHandler(interceptorHandler.AdminTokenAuthVerify))
	{
		adminAuthApiRouter.POST("/app/create", appHandler.CreateApp()) // 关联小程序
		adminAuthApiRouter.POST("/app/delete", appHandler.DeleteApp()) // 删除小程序
		adminAuthApiRouter.PUT("/app/:id", appHandler.ModifyApp())     // 修改小程序
		adminAuthApiRouter.GET("/apps", appHandler.PageList())         // 小程序列表

		adminAuthApiRouter.POST("/create", adminHandler.CreateAdmin()) // 新增客服
		adminAuthApiRouter.POST("/delete", adminHandler.DeleteAdmin()) // 删除客服
		adminAuthApiRouter.PUT("/:id", adminHandler.ModifyAdmin())     // 编辑客服
		adminAuthApiRouter.GET("/list", adminHandler.PageList())       // 客服列表
		adminAuthApiRouter.PUT("/rel_app/:id", adminHandler.RelApp())  // 关联小程序

		adminAuthApiRouter.POST("/app/keyword", keywordHandler.CreateKeyword())                      // 添加意图关键字
		adminAuthApiRouter.PUT("/app/keyword/:id", keywordHandler.ModifyKeyword())                   // 修改意图关键字
		adminAuthApiRouter.DELETE("/app/keyword/:id", keywordHandler.DeleteKeyword())                // 删除意图关键字
		adminAuthApiRouter.GET("/app/keywords", keywordHandler.KeywordPageList())                    // 获取意图关键字列表
		adminAuthApiRouter.POST("/app/keyword/material/:id", keywordHandler.CreateKeywordMaterial()) // 配置意图关键字素材
		adminAuthApiRouter.PUT("/app/keyword/material/:id", keywordHandler.ModifyKeywordMaterial())  // 修改意图关键字素材
		adminAuthApiRouter.GET("/app/keyword/materials", keywordHandler.KeywordMaterialPageList())   // 获取意图关键字素材列表

		adminAuthApiRouter.GET("/app/users", appHandler.UserPageList())               // 获取小程序用户列表
		adminAuthApiRouter.POST("/send_message", appHandler.AdminSendMessage())       // 发送消息
		adminAuthApiRouter.GET("/messages", appHandler.AppMessagePageList())          // 获取小程序用户消息列表
		adminAuthApiRouter.GET("/messages/latest", appHandler.LatestMessageByAppId()) // 根据appid获取最新消息记录
	}

	return mux, nil
}
