package router

import (
	"time"

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

	"mengpost-backend/config"
	"mengpost-backend/handlers"
	"mengpost-backend/middleware"
)

// New 构建所有路由.
func New(cfg *config.Config) *gin.Engine {
	r := gin.Default()

	r.Use(cors.New(cors.Config{
		AllowOrigins:     []string{"*"},
		AllowMethods:     []string{"GET", "POST", "PUT", "DELETE", "OPTIONS"},
		AllowHeaders:     []string{"Origin", "Content-Type", "Authorization", "X-Auth-Token"},
		ExposeHeaders:    []string{"Content-Length"},
		AllowCredentials: false,
		MaxAge:           12 * time.Hour,
	}))

	r.GET("/api/health", func(c *gin.Context) { c.JSON(200, gin.H{"ok": true}) })
	r.POST("/api/auth/verify", handlers.VerifyToken(cfg))

	auth := r.Group("/api")
	auth.Use(middleware.TokenAuth(cfg.Token))
	{
		auth.GET("/accounts", handlers.ListAccounts)
		auth.POST("/accounts", handlers.CreateAccount)
		auth.PUT("/accounts/:id", handlers.UpdateAccount)
		auth.DELETE("/accounts/:id", handlers.DeleteAccount)

		auth.GET("/accounts/:id/mailboxes", handlers.ListMailboxes)
		auth.GET("/accounts/:id/messages", handlers.ListMessages)
		auth.GET("/accounts/:id/messages/:uid", handlers.GetMessage)
		auth.POST("/accounts/:id/send", handlers.SendMessage)
		auth.GET("/accounts/:id/sent", handlers.ListSentLogs)
	}
	return r
}
