package main

import (
	"fmt"
	"github.com/google/uuid"
	"go-nkode/core"
	"log"
	"net/http"
	"os"
)

const (
	emailQueueBufferSize = 100
	maxEmailsPerSecond   = 13 // SES allows 14, but I don't want to push it
)

func main() {
	dbPath := os.Getenv("SQLITE_DB")
	if dbPath == "" {
		log.Fatalf("SQLITE_DB=/path/to/nkode.db not set")
	}
	db := core.NewSqliteDB(dbPath)
	defer db.CloseDb()
	sesClient := core.NewSESClient()
	emailQueue := core.NewEmailQueue(emailQueueBufferSize, maxEmailsPerSecond, &sesClient)
	emailQueue.Start()
	defer emailQueue.Stop()
	nkodeApi := core.NewNKodeAPI(db, emailQueue)
	AddDefaultCustomer(nkodeApi)
	handler := core.NKodeHandler{Api: nkodeApi}
	mux := http.NewServeMux()
	mux.Handle(core.CreateNewCustomer, &handler)
	mux.Handle(core.GenerateSignupResetInterface, &handler)
	mux.Handle(core.SetNKode, &handler)
	mux.Handle(core.ConfirmNKode, &handler)
	mux.Handle(core.GetLoginInterface, &handler)
	mux.Handle(core.Login, &handler)
	mux.Handle(core.RenewAttributes, &handler)
	mux.Handle(core.RandomSvgInterface, &handler)
	mux.Handle(core.RefreshToken, &handler)
	mux.Handle(core.ResetNKode, &handler)
	fmt.Println("Running on localhost:8080...")
	log.Fatal(http.ListenAndServe(":8080", corsMiddleware(mux)))
}

func corsMiddleware(next http.Handler) http.Handler {
	return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
		// Set the CORS headers
		w.Header().Set("Access-Control-Allow-Origin", "*")
		w.Header().Set("Access-Control-Allow-Methods", "GET, POST, OPTIONS, PUT, DELETE")
		w.Header().Set("Access-Control-Allow-Headers", "Content-Type, Authorization")

		// Handle preflight requests
		if r.Method == http.MethodOptions {
			w.WriteHeader(http.StatusNoContent)
			return
		}

		// Call the next handler
		next.ServeHTTP(w, r)
	})
}

func AddDefaultCustomer(api core.NKodeAPI) {
	newId, err := uuid.Parse("ed9ed6e0-082c-4b57-8d8c-f00ed6493457")
	if err != nil {
		log.Fatal(err)
	}
	customerId := core.CustomerId(newId)
	nkodePolicy := core.NewDefaultNKodePolicy()
	_, err = api.CreateNewCustomer(nkodePolicy, &customerId)
	if err != nil {
		log.Println(err)
	} else {
		log.Println("created new customer: ", newId)
	}
}
