package main

import (
	"log"
	"net/http"
	"os"
	"strconv"

	"github.com/gorilla/handlers"

	dashapi "github.com/moustachioed/dash/backend/dashapi"
	database "github.com/moustachioed/dash/backend/database"
	mapping "github.com/moustachioed/dash/backend/mapping"
	service "github.com/moustachioed/dash/backend/service"
)

func main() {
	dbHost := os.Getenv("DB_HOST")
	dbName := os.Getenv("DB_NAME")
	dbUser := os.Getenv("DB_USER")
	dbPassword := os.Getenv("DB_PASSWORD")
	dbPort := os.Getenv("DB_PORT")
	// Convert dbPort to uint16
	dbPortUint16, err := strconv.ParseUint(dbPort, 10, 16)
	if err != nil {
		log.Fatal(err)
	}

	db, err := database.NewPgDatabase(dbHost, dbUser, dbPassword, dbName, uint16(dbPortUint16))
	if err != nil {
		log.Fatal(err)
	}

	mapper := mapping.NewMapperImpl()

	JournalApiService := service.NewJournalApiService(db, mapper)
	JournalApiController := dashapi.NewJournalApiController(JournalApiService)

	PlanApiService := service.NewPlanApiService(db, mapper)
	PlanApiController := dashapi.NewPlanApiController(PlanApiService)

	TrackingApiService := service.NewTrackingApiService(db, mapper)
	TrackingApiController := dashapi.NewTrackingApiController(TrackingApiService)

	InboxApiService := service.NewInboxApiService(db, mapper)
	InboxApiController := dashapi.NewInboxApiController(InboxApiService)

	cors := handlers.CORS(
		handlers.AllowedMethods([]string{"GET", "POST", "DELETE"}),
		handlers.AllowedHeaders([]string{"Accept", "Accept-Language", "Content-Type", "Content-Language", "Origin"}),
		handlers.AllowedOrigins([]string{"*"}),
	)

	router := dashapi.NewRouter(JournalApiController, PlanApiController, TrackingApiController, InboxApiController)
	// router.Methods("GET", "POST", "DELETE", "OPTIONS")

	log.Printf("Starting server.")
	log.Fatal(http.ListenAndServe("0.0.0.0:8080", cors(router)))
}
