//
// Created by vfs on 02.05.2024.
//

package main

import (
	"context"
	"flag"
	"fmt"
	"log"
	"net/http"
	"regexp"

	"github.com/jackc/pgx/v5"

	"github.com/gorilla/sessions"

	"github.com/stripe/stripe-go/v83"

	"alfheimgame.com/alfheim/pkg/models/postgresql"
)

var users *postgresql.AccountModel
var subscriptions *postgresql.SubscriptionModel

var key = []byte("super-secret-key")
var store = sessions.NewCookieStore(key)

var emailrx = regexp.MustCompile("/^[a-zA-Z0-9.!#$%&'*+\\/=?^_`{|}~-]+@[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(?:\\.[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?)*$/")

var version string

func main() {
	addr := flag.String("addr", "127.0.0.1:8080", "HTTP network addr")
	prodAddr := flag.String("prodaddr", "127.0.0.1:4000", "HTTP network addr")
	//prodaddr := flag.String("prodaddr", "45.76.84.7:443", "HTTP network addr")

	production := flag.Bool("production", false, "Whether to use production port and TLS")

	displayVersion := flag.Bool("version", false, "Display version and exit")

	_ = addr
	flag.Parse()

	if *displayVersion {
		fmt.Printf("Version: %s\n", version)
		return
	}

	log.Println("Hello, Sailor!")

	stripe.Key = "sk_test_51PGebgKUHKCjyTmc97rfDPcvew6EhqDz2qp3U7XoAMIilAU9IVo2NO4P7ylkTvbBafFVr94trha1VYY32jRWMw2K00Yq7YJXFf"

	store.MaxAge(0)

	db, err := pgx.Connect(context.Background(), "postgres://alfheim:iK2SoVbDhdCki5n3LxGyP6zKpLspt4@losandesgames.com/alfheim")
	if err != nil {
		log.Fatal(err)
	}

	defer db.Close(context.Background())

	users = &postgresql.AccountModel{DB: db}
	subscriptions = &postgresql.SubscriptionModel{DB: db}

	mux := http.NewServeMux()

	mux.Handle("/static/", http.StripPrefix("/static/", http.FileServer(http.Dir("ui/static"))))

	mux.HandleFunc("/favicon.ico", favicon)

	mux.HandleFunc("/", home)
	mux.HandleFunc("/news", news)
	mux.HandleFunc("/login", login)
	mux.HandleFunc("/logout", logout)
	mux.HandleFunc("/register", register)
	mux.HandleFunc("/account", requireAuthenticatedUser(account))
	mux.HandleFunc("/deleteaccount", requireAuthenticatedUser(deleteAccount))
	mux.HandleFunc("/subscribe", requireAuthenticatedUser(subscribeStripe))
	mux.HandleFunc("/managebilling", requireAuthenticatedUser(manageBilling))
	mux.HandleFunc("/webhook", webhooks)

	if *production {
		// autocertManager := autocert.Manager{
		// 	Prompt:     autocert.AcceptTOS,
		// 	HostPolicy: autocert.HostWhitelist("alfheimgame.com"),
		// 	Email:      "vicenteferrarismith@gmail.com",
		// 	Cache:      autocert.DirCache("certs"),
		// }

		// server := &http.Server{
		// 	Addr:         *prodaddr,
		// 	Handler:      log_request(secure_headers(mux)),
		// 	TLSConfig:    autocertManager.TLSConfig(),
		// 	IdleTimeout:  time.Minute,
		// 	ReadTimeout:  5 * time.Second,
		// 	WriteTimeout: 10 * time.Second,
		// }

		// log.Fatal(server.ListenAndServeTLS("", ""))
		log.Fatal(http.ListenAndServe(*prodAddr, logRequest(secureHeaders(mux))))
	} else {
		log.Fatal(http.ListenAndServe(*addr, logRequest(secureHeaders(mux))))
	}
}
