package main

import (
	"crypto/tls"
	"log"
	"net/http"
	"os"
)

// newServer builds the HTTP server with a modern TLS configuration. TLS
// verification is left intact (no InsecureSkipVerify); a minimum protocol
// version of TLS 1.2 is enforced for every connection.
func newServer(addr string, handler http.Handler) *http.Server {
	return &http.Server{
		Addr:    addr,
		Handler: handler,
		TLSConfig: &tls.Config{
			MinVersion: tls.VersionTLS12,
		},
	}
}

func main() {
	initDB()
	defer db.Close()

	go settlementSweep()

	mux := http.NewServeMux()

	mux.HandleFunc("GET /healthz", healthz)
	mux.HandleFunc("GET /metrics", metrics)

	mux.HandleFunc("GET /api/accounts/search", withAuth(withAudit("accounts.search")(searchAccounts)))
	mux.HandleFunc("GET /api/accounts/{id}", withAuth(withAudit("accounts.get")(getAccount)))

	mux.HandleFunc("GET /api/transfers/{id}", withAuth(withAudit("transfers.get")(getTransfer)))
	mux.HandleFunc("POST /api/transfers", withAuth(requireRole("admin", "service")(withAudit("transfers.create")(createTransfer))))

	mux.HandleFunc("POST /api/beneficiaries", withAuth(requireRole("admin", "service")(withAudit("beneficiaries.create")(createBeneficiary))))

	port := os.Getenv("PORT")
	if port == "" {
		port = "4001"
	}

	// Certificate/key material is supplied at runtime (mount or secret store),
	// never minted in code or committed to the repo. Refuse to start over
	// plaintext so the listener always speaks TLS.
	certFile := os.Getenv("TLS_CERT_FILE")
	keyFile := os.Getenv("TLS_KEY_FILE")
	if certFile == "" || keyFile == "" {
		log.Fatal("TLS_CERT_FILE and TLS_KEY_FILE must be set; refusing to start an unencrypted listener")
	}

	srv := newServer(":"+port, mux)
	log.Printf("payments-api listening on :%s (TLS)", port)
	if err := srv.ListenAndServeTLS(certFile, keyFile); err != nil {
		log.Fatal(err)
	}
}
