//go:build ignore

package handler

import (
	"encoding/base64"
	"fmt"
	"net/http"
	"strings"
	"xboard-go/internal/database"
	"xboard-go/internal/model"
	"xboard-go/internal/protocol"

	"github.com/gin-gonic/gin"
)

func Subscribe(c *gin.Context) {
	token := c.Param("token")
	if token == "" {
		c.JSON(http.StatusForbidden, gin.H{"message": "缺少Token"})
		return
	}

	var user model.User
	if err := database.DB.Where("token = ?", token).First(&user).Error; err != nil {
		c.JSON(http.StatusForbidden, gin.H{"message": "无效的Token"})
		return
	}

	if user.Banned {
		c.JSON(http.StatusForbidden, gin.H{"message": "账号已被封禁"})
		return
	}

	var servers []model.Server
	query := database.DB.Where("`show` = ?", 1).Order("sort ASC")
	if err := query.Find(&servers).Error; err != nil {
		c.JSON(http.StatusInternalServerError, gin.H{"message": "获取节点失败"})
		return
	}

	ua := c.GetHeader("User-Agent")
	flag := c.Query("flag")

	if strings.Contains(ua, "Clash") || flag == "clash" {
		config, _ := protocol.GenerateClash(servers, user)
		c.Header("Content-Type", "application/octet-stream")
		c.String(http.StatusOK, config)
		return
	}

	if strings.Contains(ua, "sing-box") || flag == "sing-box" {
		config, _ := protocol.GenerateSingBox(servers, user)
		c.Header("Content-Type", "application/json; charset=utf-8")
		c.String(http.StatusOK, config)
		return
	}

	// Default: VMess/SS link format (Base64)
	var links []string
	for _, s := range servers {
		// Mocked link for now
		link := fmt.Sprintf("vmess://%s", s.Name)
		links = append(links, link)
	}

	encoded := base64.StdEncoding.EncodeToString([]byte(strings.Join(links, "\n")))
	c.Header("Content-Type", "text/plain; charset=utf-8")
	c.Header("Subscription-Userinfo", fmt.Sprintf("upload=%d; download=%d; total=%d; expire=%d", user.U, user.D, user.TransferEnable, user.ExpiredAt))
	c.String(http.StatusOK, encoded)
}
