//
// Copyright (C) 2024 veypi <i@veypi.com>
// 2025-03-04 16:08:06
// Distributed under terms of the MIT license.
//

package api

import (
	apiAuth "github.com/veypi/vbase/api/auth"
	"github.com/veypi/vbase/api/oauth"
	"github.com/veypi/vbase/api/role"
	"github.com/veypi/vbase/api/settings"
	"github.com/veypi/vbase/api/user"
	"github.com/veypi/vbase/api/verification"
	"github.com/veypi/vbase/cfg"
	"github.com/veypi/vbase/models"
	"github.com/veypi/vigo"
	"github.com/veypi/vigo/contrib/common"
)

var Router = vigo.NewRouter()

// PublicInfoResponse 公开信息响应
// 不需要登录即可访问，用于前端初始化
type PublicInfoResponse struct {
	AppName         string              `json:"app_name"`
	AppID           string              `json:"app_id"`
	OAuthProviders  []OAuthProviderInfo `json:"oauth_providers"`
	LoginMethods    []string            `json:"login_methods"`
	PasswordFields  []string            `json:"password_fields"`
	RegRequireEmail bool                `json:"reg_require_email"`
	RegRequirePhone bool                `json:"reg_require_phone"`
	CaptchaEnabled  bool                `json:"captcha_enabled"`
	EmailEnabled    bool                `json:"email_enabled"`
	SMSEnabled      bool                `json:"sms_enabled"`
}

// OAuthProviderInfo OAuth提供商公开信息
type OAuthProviderInfo struct {
	Code    string `json:"code"`
	Name    string `json:"name"`
	Icon    string `json:"icon"`
	Enabled bool   `json:"enabled"`
}

func init() {
	// 注册全局中间件
	Router.Use(cfg.Auth.Login())
	Router.After(common.JsonResponse, common.JsonErrorResponse)

	// 子路由挂载
	Router.Extend("/auth", apiAuth.Router)
	Router.Extend("/users", user.Router)
	Router.Extend("/roles", role.Router)
	Router.Extend("/oauth", oauth.Router)
	Router.Extend("/settings", settings.Router)
	Router.Extend("/verification", verification.Router)

	// 公开信息接口（不需要登录）
	Router.Get("/info", vigo.SkipBefore, "获取公开配置信息", getPublicInfo)

	// 404 处理
	Router.Any("/**", vigo.SkipBefore, "拦截未注册的api请求，返回404", func(x *vigo.X) error {
		return vigo.ErrNotFound
	})
}

// getPublicInfo 获取公开配置信息
func getPublicInfo(x *vigo.X) (*PublicInfoResponse, error) {
	resp := &PublicInfoResponse{}

	// 应用配置
	if name, err := models.GetSetting(models.SettingAppName); err == nil {
		resp.AppName = name
	}
	if id, err := models.GetSetting(models.SettingAppID); err == nil {
		resp.AppID = id
	}

	// 登录注册配置
	if err := models.GetSettingJSON(models.SettingAuthLoginMethods, &resp.LoginMethods); err != nil || len(resp.LoginMethods) == 0 {
		resp.LoginMethods = []string{"password"}
	}
	if err := models.GetSettingJSON(models.SettingAuthPasswordFields, &resp.PasswordFields); err != nil || len(resp.PasswordFields) == 0 {
		resp.PasswordFields = []string{"username"}
	}

	resp.RegRequireEmail, _ = models.GetSettingBool(models.SettingAuthRegRequireEmail)
	resp.RegRequirePhone, _ = models.GetSettingBool(models.SettingAuthRegRequirePhone)
	resp.CaptchaEnabled, _ = models.GetSettingBool(models.SettingSecurityCaptchaEnabled)
	resp.EmailEnabled, _ = models.GetSettingBool(models.SettingEmailEnabled)
	resp.SMSEnabled, _ = models.GetSettingBool(models.SettingSMSEnabled)

	// 获取启用的OAuth提供商
	var providers []models.OAuthProvider
	if err := cfg.DB().Where("enabled = ?", true).Order("sort_order").Find(&providers).Error; err == nil {
		for _, p := range providers {
			resp.OAuthProviders = append(resp.OAuthProviders, OAuthProviderInfo{
				Code:    p.Code,
				Name:    p.Name,
				Icon:    p.Icon,
				Enabled: p.Enabled,
			})
		}
	}

	return resp, nil
}
