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/notify"
	"wherewoof/frontend/internal/sms"
	"wherewoof/frontend/internal/storage"
)

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 credentials are configured.
	// Preferred: SMSGlobal HTTP API (SMS_USER/SMS_PASSWORD/SMS_FROM) — proven live.
	// Fallback: REST key/secret (SMS_API_KEY/SMS_API_SECRET) — unverified endpoints.
	var sender sms.Sender = sms.LogSender{}
	if u := os.Getenv("SMS_USER"); u != "" {
		sender = sms.NewHTTP(u, os.Getenv("SMS_PASSWORD"), os.Getenv("SMS_FROM"))
	} else if key := os.Getenv("SMS_API_KEY"); key != "" {
		sender = sms.New(key, os.Getenv("SMS_API_SECRET"), os.Getenv("SMS_FROM"))
	}

	// Object storage (MinIO) — nil when not configured.
	store, err := storage.NewClient()
	if err != nil {
		log.Fatal("storage:", err)
	}

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

	mux := http.NewServeMux()
	mux.Handle("GET /static/", http.StripPrefix("/static/", http.FileServer(http.Dir("static"))))
	mux.HandleFunc("GET /{$}", app.Home)
	mux.HandleFunc("GET /index.php", app.Home) // legacy old-site URL form (?x=5&productid=…)
	mux.HandleFunc("GET /about", app.About)
	mux.HandleFunc("GET /what-is-this", app.WhatIsThis)
	mux.HandleFunc("GET /contact", app.Contact)
	mux.HandleFunc("/{path...}", app.LegacyNotFound)
	mux.HandleFunc("GET /t/{tag_code}", app.PublicTag)
	mux.HandleFunc("GET /s/{code}", app.ServeShort)
	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("GET /account/tags/{id}/edit/inline", app.RequireAuth(app.EditInlinePage))
	mux.Handle("POST /account/tags/{id}/edit", app.RequireAuth(app.EditTag))
	mux.Handle("POST /account/tags/{id}/delete", app.RequireAuth(app.DeleteTag))
	mux.Handle("POST /account/tags/{id}/close", app.RequireAuth(app.CloseTag))
	mux.Handle("POST /account/tags/{id}/move", app.RequireAuth(app.MoveTag))
	mux.Handle("POST /account/tags/{id}/photo", app.RequireAuth(app.UploadPhoto))
	mux.HandleFunc("GET /photos/{key...}", app.ServePhoto)

	// Request logging: every hit (method, path, status, duration) goes to stdout
	// so we can see exactly what phones send (diagnostics for the scan flow).
	handler := http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
		start := time.Now()
		rec := &statusRecorder{ResponseWriter: w, status: 200}
		mux.ServeHTTP(rec, r)
		log.Printf("%s %s -> %d (%s)", r.Method, r.URL.RequestURI(), rec.status, time.Since(start).Round(time.Millisecond))
	})

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

type statusRecorder struct {
	http.ResponseWriter
	status int
}

func (r *statusRecorder) WriteHeader(code int) {
	r.status = code
	r.ResponseWriter.WriteHeader(code)
}
