package main

import (
	"log"

	"github.com/gin-gonic/gin"
	"github.com/joho/godotenv"

	"viplight-mrp/database"
	"viplight-mrp/handlers"
	"viplight-mrp/middleware"
)

func main() {
	database.InitDB()

	r := gin.Default()

	err := godotenv.Load()
	if err != nil {
		log.Println("Файл .env не был найден в папке backend, использую системные переменные")
	}

	// CORS Middleware
	r.Use(func(c *gin.Context) {
		c.Writer.Header().Set("Access-Control-Allow-Origin", "https://mrp.kkhome.ru")
		c.Writer.Header().Set("Access-Control-Allow-Methods", "GET, POST, PATCH, DELETE, OPTIONS")
		c.Writer.Header().Set("Access-Control-Allow-Headers", "Content-Type, Authorization")
		if c.Request.Method == "OPTIONS" {
			c.AbortWithStatus(204)
			return
		}
		c.Next()
	})

	r.POST("/register", handlers.Register)
	r.POST("/login", handlers.Login)

	protected := r.Group("/api")
	protected.Use(middleware.AuthRequired())
	{
		protected.GET("/parts/:id", handlers.GetPart)
		protected.GET("/parts", handlers.GetAllParts)
		protected.GET("/orders", handlers.GetsOrders)
		protected.POST("/parts", handlers.CreatePart)
		protected.POST("/parts/bulk", handlers.ImportParts)
		protected.PATCH("/parts/:id/status", handlers.UpdateStatus)
		protected.DELETE("/parts/:id", handlers.DeletePart)

	}

	r.Run(":8090")
}
