package main

import (
	"context"
	"log"
	"net/http"
	"os"
	"time"

	"github.com/jackc/pgx/v5/pgxpool"

	"wherewoof/frontend/internal/auth"
	"wherewoof/frontend/internal/db"
	"wherewoof/frontend/internal/handlers"
	"wherewoof/frontend/internal/sms"
)

func main() {
	dsn := os.Getenv("DATABASE_URL")
	if dsn == "" {
		log.Fatal("DATABASE_URL not set")
	}
	secret := os.Getenv("SESSION_SECRET")
	if secret == "" {
		log.Fatal("SESSION_SECRET not set")
	}
	addr := os.Getenv("ADDR")
	if addr == "" {
		addr = ":3020"
	}

	ctx := context.Background()
	pool, err := pgxpool.New(ctx, dsn)
	if err != nil {
		log.Fatal("connect:", err)
	}
	defer pool.Close()

	auth.InitSessionStore(secret)

	tpl, err := handlers.LoadTemplates()
	if err != nil {
		log.Fatal("templates:", err)
	}

	// SMS sender: log-only unless real SMSGlobal credentials are configured.
	var sender sms.Sender = sms.LogSender{}
	if key := os.Getenv("SMS_API_KEY"); key != "" {
		sender = sms.New(key, os.Getenv("SMS_API_SECRET"), os.Getenv("SMS_FROM"))
	}

	app := handlers.New(db.New(pool), tpl, sender)

	mux := http.NewServeMux()
	mux.Handle("GET /static/", http.StripPrefix("/static/", http.FileServer(http.Dir("static"))))
	mux.HandleFunc("GET /{$}", app.Home)
	mux.HandleFunc("/{path...}", http.NotFound)
	mux.HandleFunc("GET /t/{tag_code}", app.PublicTag)
	mux.HandleFunc("POST /t/{tag_code}/scan", app.Scan)
	mux.HandleFunc("POST /t/{tag_code}/contact", app.FinderContact)
	mux.HandleFunc("GET /register", app.RegisterPage)
	mux.HandleFunc("POST /register", app.Register)
	mux.HandleFunc("GET /login", app.LoginPage)
	mux.HandleFunc("POST /login", app.Login)
	mux.HandleFunc("POST /logout", app.Logout)
	mux.Handle("GET /account", app.RequireAuth(app.Account))
	mux.Handle("POST /account/tags", app.RequireAuth(app.AddTag))
	mux.Handle("GET /account/tags/{id}/edit", app.RequireAuth(app.EditTagPage))
	mux.Handle("POST /account/tags/{id}/edit", app.RequireAuth(app.EditTag))
	mux.Handle("POST /account/tags/{id}/delete", app.RequireAuth(app.DeleteTag))

	srv := &http.Server{
		Addr:         addr,
		Handler:      mux,
		ReadTimeout:  10 * time.Second,
		WriteTimeout: 10 * time.Second,
	}
	log.Println("wherewoof listening on", addr)
	log.Fatal(srv.ListenAndServe())
}
