package handler

import (
	"xboard-go/internal/database"
	"xboard-go/internal/model"
	"xboard-go/internal/service"

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

func GuestConfig(c *gin.Context) {
	Success(c, buildGuestConfig())
}

func buildGuestConfig() gin.H {
	data := gin.H{
		"tos_url":                      service.MustGetString("tos_url", ""),
		"is_email_verify":              boolToInt(service.MustGetBool("email_verify", false)),
		"is_invite_force":              boolToInt(service.MustGetBool("invite_force", false)),
		"email_whitelist_suffix":       getEmailWhitelistSuffix(),
		"is_captcha":                   boolToInt(service.MustGetBool("captcha_enable", false)),
		"captcha_type":                 service.MustGetString("captcha_type", "recaptcha"),
		"recaptcha_site_key":           service.MustGetString("recaptcha_site_key", ""),
		"recaptcha_v3_site_key":        service.MustGetString("recaptcha_v3_site_key", ""),
		"recaptcha_v3_score_threshold": service.MustGetString("recaptcha_v3_score_threshold", "0.5"),
		"turnstile_site_key":           service.MustGetString("turnstile_site_key", ""),
		"app_description":              service.MustGetString("app_description", ""),
		"app_url":                      service.GetAppURL(),
		"logo":                         service.MustGetString("logo", ""),
		"is_recaptcha":                 boolToInt(service.MustGetBool("captcha_enable", false)),
	}

	if service.IsPluginEnabled(service.PluginRealNameVerification) {
		data["real_name_verification_enable"] = true
		data["real_name_verification_notice"] = service.GetPluginConfigString(service.PluginRealNameVerification, "verification_notice", "Please complete real-name verification.")
	}

	return data
}

func GuestPlanFetch(c *gin.Context) {
	var plans []model.Plan
	if err := database.DB.Where("`show` = ? AND sell = ?", 1, 1).Order("sort ASC").Find(&plans).Error; err != nil {
		Fail(c, 500, "failed to fetch plans")
		return
	}
	
	formatted := make([]gin.H, 0, len(plans))
	for i := range plans {
		formatted = append(formatted, service.FormatPlan(&plans[i]))
	}
	
	Success(c, formatted)
}

func getEmailWhitelistSuffix() any {
	if !service.MustGetBool("email_whitelist_enable", false) {
		return 0
	}
	return service.MustGetString("email_whitelist_suffix", "")
}

func boolToInt(value bool) int {
	if value {
		return 1
	}
	return 0
}
