package main

import (
	"fmt"
	"net/http"
	"os"

	"git.schreifuchs.ch/schreifuchs/warehouse/api"
	"git.schreifuchs.ch/schreifuchs/warehouse/config"
	"git.schreifuchs.ch/schreifuchs/warehouse/controller"
	"git.schreifuchs.ch/schreifuchs/warehouse/database"
	"github.com/gorilla/mux"
	"github.com/joho/godotenv"
)

func readCfg() *config.Config {
	cfg := config.Default()

	if err := godotenv.Overload(); err != nil {
		fmt.Println("no .env file loaded")
	} else {
		fmt.Println(".env file loaded")
	}
	cfg.ReadEnv()

	return cfg
}

func main() {
	cfg := readCfg()

	fmt.Println(cfg.TOML())

	db, err := database.Init("./warehouse.db")
	if err != nil {
		fmt.Println(err)
		os.Exit(1)
	}

	controller := controller.New(db)

	apiHandler := api.Handler(api.NewStrictHandler(controller, nil))

	r := mux.NewRouter()
	r.PathPrefix("/").Handler(apiHandler)

	if err := http.ListenAndServe(fmt.Sprintf(":%d", cfg.Port), r); err != nil {
		fmt.Println(err)
		os.Exit(1)
	}

}
