package server

import (
	"net/http"

	"github.com/operator/command-center/internal/integrations/crossseed"
	"github.com/operator/command-center/internal/integrations/tqm"
)

// TqmDeps wraps the Phase 9 tqm and cross-seed clients.
type TqmDeps struct {
	Recorder   *tqm.Recorder
	Crossseed  *crossseed.Client
	TqmBinary  string
	ConfigDir  string
}

func (s *Server) handleTqmRecent(w http.ResponseWriter, r *http.Request) {
	if s.tqm == nil || s.tqm.Recorder == nil {
		http.Error(w, "tqm not configured", http.StatusServiceUnavailable)
		return
	}
	out, err := s.tqm.Recorder.RecentRuns(r.Context(), 50)
	if err != nil {
		http.Error(w, err.Error(), http.StatusInternalServerError)
		return
	}
	writeJSON(w, http.StatusOK, map[string]any{"count": len(out), "runs": out})
}

func (s *Server) handleTqmDryRun(w http.ResponseWriter, r *http.Request) {
	if s.tqm == nil {
		http.Error(w, "tqm not configured", http.StatusServiceUnavailable)
		return
	}
	out, err := tqm.DryRunCommand(r.Context(), s.tqm.TqmBinary, s.tqm.ConfigDir)
	if err != nil {
		writeJSON(w, http.StatusOK, map[string]any{"output": out, "error": err.Error()})
		return
	}
	writeJSON(w, http.StatusOK, map[string]any{"output": out})
}

func (s *Server) handleCrossseedActivity(w http.ResponseWriter, r *http.Request) {
	if s.sqlite == nil {
		http.Error(w, "sqlite required", http.StatusServiceUnavailable)
		return
	}
	rows, err := s.sqlite.QueryContext(r.Context(), `
		SELECT timestamp, target_type, target_id, details_json
		FROM audit_log
		WHERE actor = 'anonymous' AND action LIKE 'crossseed%'
		ORDER BY timestamp DESC LIMIT 200
	`)
	if err != nil {
		http.Error(w, err.Error(), http.StatusInternalServerError)
		return
	}
	defer rows.Close()
	type item struct {
		Timestamp  int64  `json:"timestamp"`
		TargetType string `json:"target_type"`
		TargetID   string `json:"target_id"`
		Details    string `json:"details_json"`
	}
	out := []item{}
	for rows.Next() {
		var i item
		if err := rows.Scan(&i.Timestamp, &i.TargetType, &i.TargetID, &i.Details); err != nil {
			http.Error(w, err.Error(), http.StatusInternalServerError)
			return
		}
		out = append(out, i)
	}
	writeJSON(w, http.StatusOK, map[string]any{"count": len(out), "events": out})
}

func (s *Server) handleCrossseedSearch(w http.ResponseWriter, r *http.Request) {
	if s.tqm == nil || s.tqm.Crossseed == nil {
		http.Error(w, "crossseed not configured", http.StatusServiceUnavailable)
		return
	}
	status, err := s.tqm.Crossseed.Search(r.Context())
	if err != nil {
		http.Error(w, err.Error(), http.StatusBadGateway)
		return
	}
	writeJSON(w, http.StatusAccepted, map[string]any{"status": status})
}
