package handlers

import (
	"net/http"
	"strings"

	"github.com/gin-gonic/gin"

	"sproutgate-backend/internal/storage"
)

// GetAdminOAuth
// @Summary OAuth 配置（脱敏）
// @Tags admin
// @Produce json
// @Security AdminToken
// @Success 200 {object} map[string]interface{}
// @Failure 401 {object} map[string]interface{}
// @Router /api/admin/oauth [get]
func (h *Handler) GetAdminOAuth(c *gin.Context) {
	cfg := h.store.GetOAuthConfig()
	c.JSON(http.StatusOK, gin.H{
		"githubEnabled":                      cfg.GitHubEnabled,
		"giteaEnabled":                       cfg.GiteaEnabled,
		"googleEnabled":                      cfg.GoogleEnabled,
		"microsoftEnabled":                   cfg.MicrosoftEnabled,
		"linuxdoEnabled":                     cfg.LinuxdoEnabled,
		"githubClientId":                     strings.TrimSpace(cfg.GitHubClientID),
		"githubClientSecretSet":              strings.TrimSpace(cfg.GitHubClientSecret) != "",
		"giteaBaseUrl":                       cfg.GiteaBaseURL,
		"giteaClientId":                      strings.TrimSpace(cfg.GiteaClientID),
		"giteaClientSecretSet":               strings.TrimSpace(cfg.GiteaClientSecret) != "",
		"googleClientId":                     strings.TrimSpace(cfg.GoogleClientID),
		"googleClientSecretSet":              strings.TrimSpace(cfg.GoogleClientSecret) != "",
		"microsoftClientId":                  strings.TrimSpace(cfg.MicrosoftClientID),
		"microsoftClientSecretSet":           strings.TrimSpace(cfg.MicrosoftClientSecret) != "",
		"microsoftTenant":                    strings.TrimSpace(cfg.MicrosoftTenant),
		"linuxdoConnectBaseUrl":              cfg.LinuxdoConnectBaseURL,
		"linuxdoClientId":                    strings.TrimSpace(cfg.LinuxdoClientID),
		"linuxdoClientSecretSet":             strings.TrimSpace(cfg.LinuxdoClientSecret) != "",
		"githubLogoUrl":                      strings.TrimSpace(cfg.GitHubLogoURL),
		"giteaLogoUrl":                       strings.TrimSpace(cfg.GiteaLogoURL),
		"googleLogoUrl":                      strings.TrimSpace(cfg.GoogleLogoURL),
		"microsoftLogoUrl":                   strings.TrimSpace(cfg.MicrosoftLogoURL),
		"linuxdoLogoUrl":                     strings.TrimSpace(cfg.LinuxdoLogoURL),
		"allowedReturnPrefixes":              cfg.AllowedReturnPrefixes,
		"allowOAuthSignUpWhenInviteRequired": cfg.AllowOAuthSignUpWhenInviteRequired,
	})
}

// PutAdminOAuth
// @Summary 更新 OAuth 配置
// @Tags admin
// @Accept json
// @Produce json
// @Security AdminToken
// @Param body body PutAdminOAuthRequest true "配置"
// @Success 200 {object} map[string]interface{}
// @Failure 400 {object} map[string]interface{}
// @Failure 401 {object} map[string]interface{}
// @Failure 500 {object} map[string]interface{}
// @Router /api/admin/oauth [put]
func (h *Handler) PutAdminOAuth(c *gin.Context) {
	var req PutAdminOAuthRequest
	if err := c.ShouldBindJSON(&req); err != nil {
		c.JSON(http.StatusBadRequest, gin.H{"error": "invalid request"})
		return
	}
	prefixes := make([]string, 0, len(req.AllowedReturnPrefixes))
	for _, p := range req.AllowedReturnPrefixes {
		p = strings.TrimSpace(p)
		if p == "" {
			continue
		}
		if !strings.HasSuffix(p, "/") {
			p += "/"
		}
		prefixes = append(prefixes, p)
	}
	if len(prefixes) == 0 {
		prefixes = append([]string(nil), h.store.GetOAuthConfig().AllowedReturnPrefixes...)
	}
	giteaBase := strings.TrimRight(strings.TrimSpace(req.GiteaBaseURL), "/")
	if giteaBase == "" {
		giteaBase = "https://git.shumengya.top"
	}
	ldBase := strings.TrimRight(strings.TrimSpace(req.LinuxdoConnectBaseURL), "/")
	if ldBase == "" {
		ldBase = "https://connect.linux.do"
	}
	out := storage.OAuthConfig{
		GitHubEnabled:                      req.GitHubEnabled,
		GiteaEnabled:                       req.GiteaEnabled,
		GoogleEnabled:                      req.GoogleEnabled,
		MicrosoftEnabled:                   req.MicrosoftEnabled,
		LinuxdoEnabled:                     req.LinuxdoEnabled,
		GitHubClientID:                     strings.TrimSpace(req.GitHubClientID),
		GitHubClientSecret:                 strings.TrimSpace(req.GitHubClientSecret),
		GiteaBaseURL:                       giteaBase,
		GiteaClientID:                      strings.TrimSpace(req.GiteaClientID),
		GiteaClientSecret:                  strings.TrimSpace(req.GiteaClientSecret),
		GoogleClientID:                     strings.TrimSpace(req.GoogleClientID),
		GoogleClientSecret:                 strings.TrimSpace(req.GoogleClientSecret),
		MicrosoftClientID:                  strings.TrimSpace(req.MicrosoftClientID),
		MicrosoftClientSecret:              strings.TrimSpace(req.MicrosoftClientSecret),
		MicrosoftTenant:                    strings.TrimSpace(req.MicrosoftTenant),
		LinuxdoConnectBaseURL:              ldBase,
		LinuxdoClientID:                    strings.TrimSpace(req.LinuxdoClientID),
		LinuxdoClientSecret:                strings.TrimSpace(req.LinuxdoClientSecret),
		GitHubLogoURL:                      strings.TrimSpace(req.GitHubLogoURL),
		GiteaLogoURL:                       strings.TrimSpace(req.GiteaLogoURL),
		GoogleLogoURL:                      strings.TrimSpace(req.GoogleLogoURL),
		MicrosoftLogoURL:                   strings.TrimSpace(req.MicrosoftLogoURL),
		LinuxdoLogoURL:                     strings.TrimSpace(req.LinuxdoLogoURL),
		AllowedReturnPrefixes:              prefixes,
		AllowOAuthSignUpWhenInviteRequired: req.AllowOAuthSignUpWhenInviteRequired,
	}
	if err := h.store.MergeUpdateOAuthConfig(out); err != nil {
		c.JSON(http.StatusInternalServerError, gin.H{"error": "failed to save oauth config"})
		return
	}
	h.GetAdminOAuth(c)
}
