package service

import (
	"encoding/json"
	"strconv"
	"strings"
	"xboard-go/internal/model"

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

var legacyPeriodMapping = map[string]string{
	"month_price":        "monthly",
	"quarter_price":      "quarterly",
	"half_year_price":    "half_yearly",
	"year_price":         "yearly",
	"two_year_price":     "two_yearly",
	"three_year_price":   "three_yearly",
	"onetime_price":      "onetime",
	"reset_price":        "reset_traffic",
}

func FormatPlan(plan *model.Plan) gin.H {
	if plan == nil {
		return nil
	}

	res := gin.H{
		"id":                   plan.ID,
		"group_id":             plan.GroupID,
		"name":                 plan.Name,
		"tags":                 parseTags(plan.Tags),
		"transfer_enable":      plan.TransferEnable,
		"speed_limit":          plan.SpeedLimit,
		"device_limit":         plan.DeviceLimit,
		"show":                 plan.Show,
		"sell":                 plan.Sell,
		"renew":                plan.Renew,
		"reset_traffic_method": plan.ResetTrafficMethod,
		"sort":                 plan.Sort,
		"created_at":           plan.CreatedAt,
		"updated_at":           plan.UpdatedAt,
		"capacity_limit":       plan.CapacityLimit,
	}

	// 1. Format Pricing (Legacy Keys + 100x Multiplier)
	var prices map[string]float64
	if plan.Prices != nil && *plan.Prices != "" {
		_ = json.Unmarshal([]byte(*plan.Prices), &prices)
	}

	for legacyKey, newPeriod := range legacyPeriodMapping {
		if price, ok := prices[newPeriod]; ok {
			res[legacyKey] = int64(price * 100)
		} else {
			res[legacyKey] = nil
		}
	}

	// 2. Format Content (Placeholders)
	content := ""
	if plan.Content != nil {
		content = *plan.Content
	}
	res["content"] = formatPlanContent(content, plan)

	return res
}

func formatPlanContent(content string, plan *model.Plan) string {
	if content == "" {
		return ""
	}

	replacements := map[string]string{
		"{{transfer}}": formatIntPtr(plan.TransferEnable),
		"{{speed}}":    formatIntPtr(plan.SpeedLimit),
		"{{devices}}":  formatIntPtr(plan.DeviceLimit),
		"{{reset_method}}": getResetMethodText(plan.ResetTrafficMethod),
	}

	for k, v := range replacements {
		content = strings.ReplaceAll(content, k, v)
	}

	return content
}

func formatIntPtr(val *int) string {
	if val == nil {
		return "无限制" // Localized or default
	}
	return strings.TrimSpace(strconv.Itoa(*val))
}

func getResetMethodText(method *int) string {
	if method == nil {
		return "每月重置"
	}
	switch *method {
	case 0:
		return "每月1号"
	case 1:
		return "按月重置"
	case 2:
		return "不重置"
	case 3:
		return "每年1月1日"
	case 4:
		return "按年重置"
	default:
		return "按月重置"
	}
}

func parseTags(tags *string) []string {
	if tags == nil || *tags == "" {
		return []string{}
	}
	var res []string
	if err := json.Unmarshal([]byte(*tags), &res); err == nil {
		return res
	}
	return strings.Split(*tags, ",")
}
