package cmd

import (
	"context"

	"github.com/gin-gonic/gin"
	"github.com/jackc/pgx/v5/pgxpool"
	"github.com/robfig/cron"
	healthcheck "github.com/tavsec/gin-healthcheck"
	"github.com/tavsec/gin-healthcheck/checks"
	"github.com/tavsec/gin-healthcheck/config"

	controller "gitlab.ost.ch/marketminds/marketminds/pkg/controller"
	datasql "gitlab.ost.ch/marketminds/marketminds/pkg/data/sql"
)

func StartServer() {
	connectionPool, err := pgxpool.NewWithConfig(context.Background(), datasql.Config())
	if err != nil {
		panic(err)
	}
	defer connectionPool.Close()

	sqlDbInstance := datasql.NewSqlInstance(connectionPool)
	controller := controller.NewController(sqlDbInstance)

	// execute news import every minute
	c := cron.New()
	c.AddFunc("0 * * * * *", controller.ImportJob)
	c.Start()
	defer c.Stop()

	r := gin.Default()

	// enable cors
	r.Use(func(c *gin.Context) {
		c.Writer.Header().Set("Access-Control-Allow-Origin", "http://localhost:3001")
		c.Writer.Header().Set("Access-Control-Allow-Methods", "GET, POST, PUT, DELETE, OPTIONS")
		c.Writer.Header().Set("Access-Control-Allow-Headers", "Content-Type, Content-Length, Accept-Encoding, X-CSRF-Token, Authorization")
		if c.Request.Method == "OPTIONS" {
			c.AbortWithStatus(204)
			return
		}
		c.Next()
	})

	// healthcheck endpoint for monitoring ("/healthz")
	healthcheck.New(r, config.DefaultConfig(), []checks.Check{})

	r.GET("/status", controller.Status)

	apiGroup := r.Group("/api")
	{

		apiGroup.GET("/import", controller.Import)

		apiGroup.GET("/news-channel", controller.GetAllNewsChannel)
		apiGroup.GET("/news-channel/:id", controller.GetNewsChannelById)

		// for paging we can use link with this /news?page=:id&limit=:id
		apiGroup.GET("/news", controller.GetNews)
		apiGroup.GET("/news/:id", controller.GetNewsItemById)

		apiGroup.GET("/tags", controller.GetAllNamedEntities)
		apiGroup.GET("/tags/:id", controller.GetNamedEntity)
	}

	r.Run()
}
