package api

import (
	"context"
	"errors"
	"net/http"

	"github.com/gin-gonic/gin"
	flagsvc "github.com/tidbcloud/account/internel/svc/flag"
	"github.com/tidbcloud/tiinf/errs"
)

func ConfigFeatureWhitelist(c *gin.Context) {
	ctx := c.Request.Context()
	req := &AdminConfigFeatureWhitelistReq{}
	if err := c.ShouldBindJSON(req); err != nil {
		Fail(c, err, http.StatusBadRequest)
		return
	}
	if req.FeatureName == "" {
		Fail(c, errors.New("feature_name is blank"), http.StatusBadRequest)
		return
	}

	svc := flagsvc.GetFeatureFlagSvc()
	featureInfo, err := svc.GetFeatureFlagByName(ctx, req.FeatureName)
	if err != nil {
		if errors.Is(err, errs.ErrNotFound) {
			featureInfo = nil
			err = nil
		} else {
			Fail(c, err, http.StatusInternalServerError)
			return
		}
	}
	if featureInfo == nil {
		if req.CreateNewFeature {
			err = creatNewFeature(ctx, req)
			if err != nil {
				Fail(c, err, http.StatusInternalServerError)
			} else {
				Success(c, "config success", http.StatusOK)
			}
		} else {
			Fail(c, errors.New("feature not found"), http.StatusNotFound)
		}
		return
	}

	var updateErr error = nil
	if req.EnableAllOrgs {
		param := flagsvc.CreateFeatureFlagParam{
			FlagName: req.FeatureName,
			MinOrgID: "0",
		}
		updateErr = svc.UpdateFeatureFlag(ctx, &param)
	} else if len(req.OrgIDs) > 0 {
		updateErr = svc.ConfigFeatureFlagOrg(ctx, req.FeatureName, req.OrgIDs)
	}
	if updateErr != nil {
		Fail(c, err, http.StatusInternalServerError)
	} else {
		Success(c, "config success", http.StatusOK)
	}
}

func creatNewFeature(ctx context.Context, req *AdminConfigFeatureWhitelistReq) error {
	param := &flagsvc.CreateFeatureFlagParam{
		FlagName:    req.FeatureName,
		Description: req.FeatureName,
		Owner:       "system",
		OrgIDs:      req.OrgIDs,
	}
	if req.EnableAllOrgs {
		param.MinOrgID = "0"
	}

	return flagsvc.GetFeatureFlagSvc().CreateFeatureFlag(ctx, param)
}

type AdminConfigFeatureWhitelistReq struct {
	FeatureName      string   `json:"feature_name"`
	OrgIDs           []uint64 `json:"org_ids"`
	EnableAllOrgs    bool     `json:"enable_all_orgs"`
	CreateNewFeature bool     `json:"create_new_feature"`
}
