package web

import (
	"embed"
	"encoding/json"
	"fmt"
	"html/template"
	"log"
	"net/http"

	"github.com/pfeifferj/container-mom-go/pkg/operator"
)

//go:embed templates/* static/*
var content embed.FS

// Server represents the HTTP server for the container-mom API
type Server struct {
	op       *operator.Operator
	addr     string
	template *template.Template
}

// NewServer creates a new HTTP server instance
func NewServer(op *operator.Operator, addr string) (*Server, error) {
	tmpl, err := template.ParseFS(content, "templates/*.html")
	if err != nil {
		return nil, fmt.Errorf("failed to parse templates: %v", err)
	}

	return &Server{
		op:       op,
		addr:     addr,
		template: tmpl,
	}, nil
}

// Start begins listening for HTTP requests
func (s *Server) Start() error {
	http.HandleFunc("/", s.handleIndex)
	http.HandleFunc("/api/containers", s.handleContainers)

	// Serve static files
	fs := http.FileServer(http.FS(content))
	http.Handle("/static/", fs)

	log.Printf("Starting web server on %s", s.addr)
	return http.ListenAndServe(s.addr, nil)
}

func (s *Server) handleIndex(w http.ResponseWriter, r *http.Request) {
	containers, err := s.op.GetContainers()
	if err != nil {
		http.Error(w, err.Error(), http.StatusInternalServerError)
		return
	}

	data := struct {
		Containers []operator.ContainerStatus
	}{
		Containers: containers,
	}

	if err := s.template.ExecuteTemplate(w, "index.html", data); err != nil {
		http.Error(w, err.Error(), http.StatusInternalServerError)
	}
}

func (s *Server) handleContainers(w http.ResponseWriter, r *http.Request) {
	containers, err := s.op.GetContainers()
	if err != nil {
		http.Error(w, err.Error(), http.StatusInternalServerError)
		return
	}

	if err := json.NewEncoder(w).Encode(containers); err != nil {
		http.Error(w, "Failed to encode response", http.StatusInternalServerError)
		return
	}
}
