package web

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

	"ymhut-box/server/unified-management/internal/db"
	"ymhut-box/server/unified-management/internal/feedback"
)

func (r *router) handleLegacyMediaTypes(w http.ResponseWriter, req *http.Request) {
	catalog, err := r.sources.Catalog(false)
	if err != nil {
		writeError(w, http.StatusInternalServerError, "MEDIA_TYPES_FAILED", err)
		return
	}
	writeJSON(w, http.StatusOK, catalog)
}

func (r *router) handleSourceCall(w http.ResponseWriter, req *http.Request) {
	if req.Method != http.MethodPost {
		writeError(w, http.StatusMethodNotAllowed, "METHOD_NOT_ALLOWED", errors.New("POST required"))
		return
	}
	var body db.SourceCall
	if err := json.NewDecoder(req.Body).Decode(&body); err != nil {
		writeError(w, http.StatusBadRequest, "INVALID_PAYLOAD", err)
		return
	}
	body.Client = firstNonEmpty(body.Client, req.UserAgent())
	if err := r.store.RecordSourceCall(body); err != nil {
		writeError(w, http.StatusInternalServerError, "SOURCE_CALL_FAILED", err)
		return
	}
	writeJSON(w, http.StatusOK, map[string]any{"ok": true})
}

func (r *router) handleFeedbackSubmit(w http.ResponseWriter, req *http.Request) {
	item, err := r.feedback.Submit(req)
	if err != nil {
		code, status := feedback.LegacyError(err)
		_ = r.store.InsertAudit(db.AuditLog{Actor: "client", Type: "feedback.rejected", Target: "feedback", Message: "旧反馈提交失败：" + localizedErrorMessage(code, err.Error()), IP: req.RemoteAddr, UserAgent: req.UserAgent()})
		writeError(w, status, code, err)
		return
	}
	_ = r.store.InsertAudit(db.AuditLog{Actor: "client", Type: "feedback.created", Target: item.Code, Message: "客户端提交反馈：" + item.Title, IP: req.RemoteAddr, UserAgent: req.UserAgent()})
	writeJSON(w, http.StatusOK, legacyFeedbackStatus(item, feedback.DuplicateSubmission(req)))
}

func (r *router) handleFeedbackStatus(w http.ResponseWriter, req *http.Request) {
	code := feedback.NormalizeCode(req.URL.Query().Get("code"))
	if code == "" {
		writeError(w, http.StatusBadRequest, "INVALID_CODE", errors.New("code is required"))
		return
	}
	item, err := r.store.GetFeedback(code)
	if err != nil {
		writeError(w, http.StatusNotFound, "NOT_FOUND", err)
		return
	}
	writeJSON(w, http.StatusOK, legacyFeedbackStatus(item, false))
}

func feedbackStatusLabel(status string) string {
	switch strings.ToLower(strings.TrimSpace(status)) {
	case "processing", "in_progress":
		return "处理中"
	case "closed", "resolved", "done":
		return "已关闭"
	case "rejected":
		return "已驳回"
	default:
		return "已接收"
	}
}
