package web

import (
	"encoding/json"
	"errors"
	"net/http"
	"strings"

	"ymhut-box/server/unified-management/internal/legacy"
)

func (r *router) handleAdminLegacy(w http.ResponseWriter, req *http.Request) {
	path := cleanPath(req.URL.Path)
	name := ""
	switch {
	case strings.HasPrefix(path, "/api/admin/legacy/update-info"):
		name = "update-info"
	case strings.HasPrefix(path, "/api/admin/legacy/media-types"):
		name = "media-types"
	default:
		parts := strings.Split(strings.TrimPrefix(path, "/api/admin/legacy/"), "/")
		if len(parts) > 0 {
			name = parts[0]
		}
	}
	if name == "" {
		http.NotFound(w, req)
		return
	}
	if req.Method == http.MethodGet && (path == "/api/admin/legacy/update-info" || path == "/api/admin/legacy/media-types") {
		doc, err := r.legacy.Get(req.Context(), name)
		if err != nil {
			writeError(w, http.StatusBadRequest, "LEGACY_GET_FAILED", err)
			return
		}
		writeJSON(w, http.StatusOK, map[string]any{"ok": true, "document": doc})
		return
	}
	if req.Method == http.MethodPut && (path == "/api/admin/legacy/update-info" || path == "/api/admin/legacy/media-types") {
		var body legacy.SaveRequest
		if err := json.NewDecoder(req.Body).Decode(&body); err != nil {
			writeError(w, http.StatusBadRequest, "INVALID_PAYLOAD", err)
			return
		}
		doc, err := r.legacy.Save(req.Context(), name, body, "admin")
		if err != nil {
			writeError(w, http.StatusBadRequest, "LEGACY_SAVE_FAILED", err)
			return
		}
		if name == "media-types" {
			_ = r.sources.ImportLegacyMediaTypes(req.Context())
		}
		if name == "update-info" {
			r.syncNoticeFromLegacyUpdateInfo(req, doc.Raw)
		}
		writeJSON(w, http.StatusOK, map[string]any{"ok": true, "document": doc})
		return
	}
	if req.Method == http.MethodPost && strings.HasSuffix(path, "/validate") {
		var body legacy.SaveRequest
		if err := json.NewDecoder(req.Body).Decode(&body); err != nil {
			writeError(w, http.StatusBadRequest, "INVALID_PAYLOAD", err)
			return
		}
		doc, err := r.legacy.Validate(req.Context(), name, body)
		if err != nil {
			writeError(w, http.StatusBadRequest, "LEGACY_VALIDATE_FAILED", err)
			return
		}
		writeJSON(w, http.StatusOK, map[string]any{"ok": true, "document": doc})
		return
	}
	if req.Method == http.MethodPost && strings.HasSuffix(path, "/restore") {
		var body struct {
			RevisionID int64 `json:"revisionId"`
		}
		if err := json.NewDecoder(req.Body).Decode(&body); err != nil || body.RevisionID <= 0 {
			writeError(w, http.StatusBadRequest, "INVALID_PAYLOAD", errors.New("revisionId is required"))
			return
		}
		doc, err := r.legacy.Restore(req.Context(), name, body.RevisionID, "admin")
		if err != nil {
			writeError(w, http.StatusBadRequest, "LEGACY_RESTORE_FAILED", err)
			return
		}
		if name == "media-types" {
			_ = r.sources.ImportLegacyMediaTypes(req.Context())
		}
		if name == "update-info" {
			r.syncNoticeFromLegacyUpdateInfo(req, doc.Raw)
		}
		writeJSON(w, http.StatusOK, map[string]any{"ok": true, "document": doc})
		return
	}
	http.NotFound(w, req)
}

func (r *router) syncNoticeFromLegacyUpdateInfo(req *http.Request, raw string) {
	if r.notices == nil {
		return
	}
	_ = r.notices.SyncFromLegacyUpdateInfo(req.Context(), raw, "admin")
}
