package handler

import (
	"net/http"
	"strings"

	"aijianzhan/platform/internal/audit"
	"aijianzhan/platform/internal/authx"
	"aijianzhan/platform/internal/meta"
	"aijianzhan/platform/internal/svc"

	"github.com/zeromicro/go-zero/rest/httpx"
)

// platformEnsureImportHandler Z9e：超管扫全库已发布模块补齐 import/export。
// POST /api/v1/platform/apps/ensure-import?dry_run=1
func platformEnsureImportHandler(svcCtx *svc.ServiceContext) http.HandlerFunc {
	return func(w http.ResponseWriter, r *http.Request) {
		dry := r.URL.Query().Get("dry_run") == "1" || strings.EqualFold(r.URL.Query().Get("dry_run"), "true")
		res, err := meta.BackfillDefaultImportExport(r.Context(), svcCtx.Meta, dry)
		if err != nil {
			authx.WriteError(w, http.StatusBadRequest, err.Error())
			return
		}
		if svcCtx.Audit != nil {
			_ = svcCtx.Audit.Log(r.Context(), 0, authx.UserID(r.Context()), "apps.ensure_import", audit.DetailJSON(res))
		}
		httpx.OkJson(w, res)
	}
}

// adminEnsureImportHandler Z9e：租户管理员对本公司已发布模块一键开启导入。
// POST /api/v1/admin/apps/ensure-import?dry_run=1
func adminEnsureImportHandler(svcCtx *svc.ServiceContext) http.HandlerFunc {
	return func(w http.ResponseWriter, r *http.Request) {
		dry := r.URL.Query().Get("dry_run") == "1" || strings.EqualFold(r.URL.Query().Get("dry_run"), "true")
		tid := authx.TenantID(r.Context())
		res, err := meta.BackfillDefaultImportExportForTenant(r.Context(), svcCtx.Meta, tid, dry)
		if err != nil {
			authx.WriteError(w, http.StatusBadRequest, err.Error())
			return
		}
		if svcCtx.Audit != nil {
			_ = svcCtx.Audit.Log(r.Context(), tid, authx.UserID(r.Context()), "apps.ensure_import", audit.DetailJSON(res))
		}
		httpx.OkJson(w, res)
	}
}
