package main

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

	"golang.org/x/crypto/bcrypt"

	"podstalk/handler"
	"podstalk/store"
)

//go:embed template/*.html
var templateFS embed.FS

//go:embed static/*
var staticFS embed.FS

func main() {
	if len(os.Args) > 1 && os.Args[1] == "adduser" {
		runAddUser()
		return
	}

	dbPath := os.Getenv("PODSTALK_DB")
	if dbPath == "" {
		dbPath = "podstalk.db"
	}

	uploadDir := os.Getenv("PODSTALK_UPLOAD_DIR")
	if uploadDir == "" {
		uploadDir = "uploads"
	}

	baseURL := os.Getenv("PODSTALK_LINK")
	if baseURL == "" {
		baseURL = "http://localhost:8080"
	}

	st, err := store.New(dbPath)
	if err != nil {
		log.Fatalf("failed to open database: %v", err)
	}
	defer st.Close()

	tmpl, err := template.New("").ParseFS(templateFS, "template/*.html")
	if err != nil {
		log.Fatalf("failed to parse templates: %v", err)
	}
	tpl := handler.NewTemplates(tmpl)

	sessions := handler.NewSessionStore()

	authMid := &handler.AuthMiddleware{Store: st, Sessions: sessions}

	authH := &handler.AuthHandler{Store: st, Sessions: sessions, Tpl: tpl}
	epH := &handler.EpisodeHandler{
		Store:     st,
		Tpl:       tpl,
		UploadDir: uploadDir,
		BaseURL:   baseURL,
	}
	setH := &handler.SettingsHandler{
		Store:     st,
		UploadDir: uploadDir,
	}
	rssH := &handler.RSSHandler{
		Store: st,
		Link:  baseURL,
	}
	importH := &handler.ImportHandler{
		Store:     st,
		Tpl:       tpl,
		UploadDir: uploadDir,
	}

	// Auth routes.
	http.HandleFunc("/signup", authMid.RedirectIfAuthed(authH.ServeSignup))
	http.HandleFunc("/signin", authMid.RedirectIfAuthed(authH.ServeSignin))
	http.HandleFunc("/signout", authH.ServeSignout)

	// Protected routes.
	http.HandleFunc("/", authMid.RequireAuth(epH.ServeDashboard))
	http.HandleFunc("/episodes/new", authMid.RequireAuth(epH.ServeNew))
	http.HandleFunc("/episodes/edit", authMid.RequireAuth(epH.ServeEdit))
	http.HandleFunc("/episodes/delete", authMid.RequireAuth(epH.ServeDelete))
	http.HandleFunc("/settings", authMid.RequireAuth(setH.ServeSettings))
	http.HandleFunc("/import", authMid.RequireAuth(importH.ServeImport))

	// Public RSS: /rss/my-slug or /rss?slug=my-slug or /rss?user=N (legacy)
	http.HandleFunc("/rss", rssH.ServeRSS)
	http.HandleFunc("GET /rss/{slug}", rssH.ServeRSS)

	// Public uploaded files.
	http.HandleFunc("/uploads/", epH.ServeUpload)
	// Static files.
	http.Handle("/static/", http.FileServer(http.FS(staticFS)))

	port := envOrDefault("PORT", "8080")
	addr := fmt.Sprintf(":%s", port)
	log.Printf("Podstalk listening on http://0.0.0.0%s", addr)
	log.Fatal(http.ListenAndServe(addr, nil))
}

func runAddUser() {
	if len(os.Args) != 4 {
		log.Fatalf("Usage: podstalk adduser <email> <password>")
	}

	email := os.Args[2]
	password := os.Args[3]

	dbPath := os.Getenv("PODSTALK_DB")
	if dbPath == "" {
		dbPath = "podstalk.db"
	}

	st, err := store.New(dbPath)
	if err != nil {
		log.Fatalf("failed to open database: %v", err)
	}
	defer st.Close()

	hash, err := bcrypt.GenerateFromPassword([]byte(password), bcrypt.DefaultCost)
	if err != nil {
		log.Fatalf("failed to hash password: %v", err)
	}

	userID, err := st.CreateUser(email, string(hash))
	if err != nil {
		log.Fatalf("failed to create user: %v", err)
	}

	log.Printf("User created (id=%d)", userID)
}

func envOrDefault(key, def string) string {
	if v := os.Getenv(key); v != "" {
		return v
	}
	return def
}
