package policy

import (
	"errors"
	"strings"

	"gorm.io/gorm"

	"ops-assistant/models"
)

type GateRequest struct {
	NeedFlag       string
	RequireConfirm bool
	ConfirmToken   string
	ExpectedToken  string
	AllowDryRun    bool
	DryRun         bool
}

func ParseCommonFlags(text string) (dryRun bool, confirmToken string) {
	parts := strings.Fields(strings.TrimSpace(text))
	for i := 0; i < len(parts); i++ {
		if parts[i] == "--dry-run" {
			dryRun = true
		}
		if parts[i] == "--confirm" && i+1 < len(parts) {
			confirmToken = strings.TrimSpace(parts[i+1])
			i++
		}
	}
	return
}

func FlagEnabled(db *gorm.DB, key string) bool {
	if strings.TrimSpace(key) == "" {
		return true
	}
	var ff models.FeatureFlag
	if err := db.Where("key = ?", key).First(&ff).Error; err != nil {
		return false
	}
	return ff.Enabled
}

func CheckGate(db *gorm.DB, req GateRequest) error {
	if strings.TrimSpace(req.NeedFlag) != "" && !FlagEnabled(db, req.NeedFlag) {
		return errors.New("feature flag 未启用: " + req.NeedFlag)
	}
	if req.RequireConfirm {
		if strings.TrimSpace(req.ConfirmToken) == "" {
			return errors.New("缺少 --confirm <token>")
		}
		if strings.TrimSpace(req.ExpectedToken) != "" && strings.TrimSpace(req.ConfirmToken) != strings.TrimSpace(req.ExpectedToken) {
			return errors.New("确认 token 无效")
		}
	}
	if req.DryRun && !req.AllowDryRun {
		return errors.New("当前命令不允许 dry-run")
	}
	return nil
}
