package router

import (
	"strings"
	"time"

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

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

func corsConfig(cfg *config.Config) cors.Config {
	c := cors.Config{
		AllowMethods: []string{
			"GET", "POST", "PUT", "PATCH", "DELETE", "HEAD", "OPTIONS",
		},
		AllowHeaders: []string{
			"Origin", "Content-Length", "Content-Type", "Accept",
			"Authorization", "X-Auth-Token", "X-Requested-With",
		},
		ExposeHeaders:    []string{"Content-Length"},
		AllowCredentials: false,
		MaxAge:           12 * time.Hour,
	}
	raw := strings.TrimSpace(cfg.CORSAllowOrigins)
	if raw == "" || raw == "*" {
		// 生产/跨域穿透：允许任意 Origin（与 AllowCredentials=false 搭配，适合前后端分域名）
		c.AllowOriginFunc = func(origin string) bool { return true }
		return c
	}
	parts := strings.Split(raw, ",")
	for _, p := range parts {
		p = strings.TrimSpace(p)
		if p != "" {
			c.AllowOrigins = append(c.AllowOrigins, p)
		}
	}
	if len(c.AllowOrigins) == 0 {
		c.AllowOriginFunc = func(origin string) bool { return true }
	}
	return c
}

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

	r.Use(cors.New(corsConfig(cfg)))

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

	auth := r.Group("/api")
	auth.Use(middleware.TokenAuth(cfg.Token))
	{
		auth.GET("/oauth/microsoft/start", handlers.MicrosoftOAuthStart(cfg))
		auth.POST("/oauth/microsoft/finish", handlers.MicrosoftOAuthFinish())

		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
}
