package route

import (
	"crawler/controller"
	"crawler/service"
	"fmt"
	"time"

	"github.com/gin-gonic/gin"
)

var (
	MovieController   = new(controller.Movie)
	CompanyController = new(controller.Company)
	CronController    = new(controller.Cron)
	G2AController     = new(controller.G2A)
)

// 라우터 설정
func SetRoute(app *gin.Engine) {
	NoRoute(app)      // 404
	CronRoute(app)    // Cron schedule
	MovieRoute(app)   // 영화 API
	CompanyRoute(app) // 영화사 API
	G2ARoute(app)     // G2A API

	defer func() {
		if c := recover(); c != nil {
			fmt.Println("Recover route execute !!")
		}
	}()

	app.GET("/ping", func(c *gin.Context) {
		c.JSON(200, gin.H{
			"message": "pong",
		})
	})

	app.GET("/db", func(c *gin.Context) {
		t := time.Now()
		var x int
		_ = service.DB_MOVIEW.SQLDB.QueryRow("SELECT 1").Scan(&x)
		c.JSON(200, gin.H{"ms": time.Since(t).Milliseconds()})
	})
}

func NoRoute(app *gin.Engine) {
	app.NoRoute(func(c *gin.Context) {
		c.File("index.html")
	})
}

func MovieRoute(app *gin.Engine) {
	r := app.Group("/movie")
	r.GET("/searchDailyBoxOfficeList", MovieController.SearchDailyBoxOfficeList)
	r.GET("/searchWeeklyBoxOfficeList", MovieController.SearchWeeklyBoxOfficeList)
	r.GET("/searchMovieList", MovieController.SearchMovieList)
	r.GET("/searchDailyInfo", MovieController.SearchDailyInfo)
	r.GET("/searchWeeklyInfo", MovieController.SearchWeeklyInfo)
	r.GET("/searchMovieInfo", MovieController.SearchMovieInfo)
}

func CompanyRoute(app *gin.Engine) {
	r := app.Group("/company")
	r.GET("/searchCompanyList", CompanyController.SearchCompanyList)
	r.GET("/searchCompanyInfo", CompanyController.SearchCompanyInfo)
}

func CronRoute(app *gin.Engine) {
	r := app.Group("/cron")
	r.GET("/list", CronController.List)
	r.GET("/info", CronController.Info)
	r.GET("/detail", CronController.Detail)
	r.GET("/companyList", CronController.CompanyList)
	r.GET("/companyInfo", CronController.CompanyInfo)
	//r.GET("/stats", CronController.Stats)
}

func G2ARoute(app *gin.Engine) {
	r := app.Group("/g2a")
	r.GET("/products", G2AController.Products)
	r.GET("/checkOutOfStock", G2AController.CheckOutOfStock)
	r.GET("/order", G2AController.Order)
}
