package portal

import (
	"embed"
	"html/template"
	"log"
	"net/http"

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

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

type Portal struct {
	operator   *operator.Operator
	templates  *template.Template
	router     *mux.Router
	listenAddr string
}

func NewPortal(op *operator.Operator, addr string) (*Portal, error) {
	tmpl, err := template.ParseFS(content, "templates/*.html")
	if err != nil {
		return nil, err
	}

	p := &Portal{
		operator:   op,
		templates:  tmpl,
		router:     mux.NewRouter(),
		listenAddr: addr,
	}

	p.setupRoutes()
	return p, nil
}

func (p *Portal) setupRoutes() {
	// Static files
	p.router.PathPrefix("/static/").Handler(http.FileServer(http.FS(content)))

	// Pages
	p.router.HandleFunc("/", p.handleDashboard).Methods("GET")
	p.router.HandleFunc("/deployments", p.handleDeployments).Methods("GET")
	p.router.HandleFunc("/deployments/new", p.handleNewDeployment).Methods("GET", "POST")
	p.router.HandleFunc("/deployments/{name}", p.handleDeploymentDetail).Methods("GET")
	p.router.HandleFunc("/billing", p.handleBilling).Methods("GET")

	// API endpoints
	api := p.router.PathPrefix("/api/v1").Subrouter()
	api.HandleFunc("/deployments", p.handleAPIDeployments).Methods("GET", "POST")
	api.HandleFunc("/deployments/{name}", p.handleAPIDeploymentDetail).Methods("GET", "PUT", "DELETE")
	api.HandleFunc("/deployments/{name}/logs", p.handleAPIDeploymentLogs).Methods("GET")
}

func (p *Portal) Start() error {
	log.Printf("Starting web portal on %s", p.listenAddr)
	return http.ListenAndServe(p.listenAddr, p.router)
}

// Handler implementations...
