package main

import (
	"log"
	"net/http"
	"time"

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

	"mengyastore-backend/internal/auth"
	"mengyastore-backend/internal/config"
	"mengyastore-backend/internal/handlers"
	"mengyastore-backend/internal/storage"
)

func main() {
	cfg, err := config.Load("data/json/settings.json")
	if err != nil {
		log.Fatalf("load config failed: %v", err)
	}

	store, err := storage.NewJSONStore("data/json/products.json")
	if err != nil {
		log.Fatalf("init store failed: %v", err)
	}
	orderStore, err := storage.NewOrderStore("data/json/orders.json")
	if err != nil {
		log.Fatalf("init order store failed: %v", err)
	}
	siteStore, err := storage.NewSiteStore("data/json/site.json")
	if err != nil {
		log.Fatalf("init site store failed: %v", err)
	}

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

	r.GET("/api/health", func(c *gin.Context) {
		c.JSON(http.StatusOK, gin.H{"status": "ok"})
	})

	authClient := auth.NewSproutGateClient(cfg.AuthAPIURL)

	publicHandler := handlers.NewPublicHandler(store)
	adminHandler := handlers.NewAdminHandler(store, cfg)
	orderHandler := handlers.NewOrderHandler(store, orderStore, authClient)
	statsHandler := handlers.NewStatsHandler(orderStore, siteStore)

	r.GET("/api/products", publicHandler.ListProducts)
	r.POST("/api/checkout", orderHandler.CreateOrder)
	r.POST("/api/products/:id/view", publicHandler.RecordProductView)
	r.GET("/api/stats", statsHandler.GetStats)
	r.POST("/api/site/visit", statsHandler.RecordVisit)
	r.GET("/api/orders", orderHandler.ListMyOrders)
	r.POST("/api/orders/:id/confirm", orderHandler.ConfirmOrder)

	r.GET("/api/admin/token", adminHandler.GetAdminToken)
	r.GET("/api/admin/products", adminHandler.ListAllProducts)
	r.POST("/api/admin/products", adminHandler.CreateProduct)
	r.PUT("/api/admin/products/:id", adminHandler.UpdateProduct)
	r.PATCH("/api/admin/products/:id/status", adminHandler.ToggleProduct)
	r.DELETE("/api/admin/products/:id", adminHandler.DeleteProduct)

	log.Println("萌芽小店后端启动于 http://localhost:8080")
	if err := r.Run(":8080"); err != nil {
		log.Fatalf("server run failed: %v", err)
	}
}
