package main

import (
	"api/database"
	"api/globals"
	"api/routes"
	"io"
	"log"
	"os"

	"github.com/gofiber/fiber/v2"
	"github.com/gofiber/fiber/v2/middleware/cors"
	"github.com/gofiber/fiber/v2/middleware/logger"
)

func main() {
	logFile, err := os.OpenFile("api.log", os.O_CREATE|os.O_APPEND|os.O_RDWR, 0666)

	if err != nil {
		panic(err)
	}
	mw := io.MultiWriter(os.Stdout, logFile)
	log.SetOutput(mw)

	log.Println("Starting API", globals.API_VERSION)
	log.Println("OS:", os.Getenv("OS"))

	app := fiber.New(fiber.Config{
		StrictRouting:         false,
		DisableStartupMessage: true,
	})

	app.Use(cors.New(cors.Config{
		AllowCredentials: true,
		AllowOrigins:     "http://*, https://*",
		AllowHeaders:     "Origin, Content-Type, Accept, Authorization, Access-Control-Allow-Origin",
		AllowMethods:     "GET, POST, PUT, DELETE, PATCH, HEAD, OPTIONS",
	}))

	file, err := os.OpenFile("./api-homolog.log", os.O_CREATE|os.O_WRONLY|os.O_APPEND, 0666)

	if err != nil {
		log.Fatalf("error opening file: %v", err)
	}

	defer file.Close()

	app.Use(logger.New(logger.Config{
		Output: file,
	}))

	if err := database.ConnectDB(); err != nil {
		panic("Could not connect to database")
	}

	routes.Setup(app)

	log.Println("Server started in port " + os.Getenv("API_PORT"))
	if erro := app.Listen(":" + os.Getenv("API_PORT")); err != nil {
		panic(erro)
	}
}
