package api

import (
	"net/http"
	"strings"

	"srs.epita.fr/fic-server/admin/sync"

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

func declareRepositoriesRoutes(router *gin.RouterGroup) {
	if gi, ok := sync.GlobalImporter.(sync.GitImporter); ok {
		router.GET("/repositories", func(c *gin.Context) {
			mod, err := gi.GetSubmodules()
			if err != nil {
				c.AbortWithStatusJSON(http.StatusInternalServerError, gin.H{"errmsg": err.Error()})
				return
			}
			c.JSON(http.StatusOK, gin.H{"repositories": mod})
		})

		router.GET("/repositories/*repopath", func(c *gin.Context) {
			repopath := strings.TrimPrefix(c.Param("repopath"), "/")

			mod, err := gi.GetSubmodule(repopath)
			if err != nil {
				c.AbortWithStatusJSON(http.StatusInternalServerError, gin.H{"errmsg": err.Error()})
				return
			}
			c.JSON(http.StatusOK, mod)
		})

		router.POST("/repositories/*repopath", func(c *gin.Context) {
			repopath := strings.TrimPrefix(c.Param("repopath"), "/")

			mod, err := gi.IsRepositoryUptodate(repopath)
			if err != nil {
				c.AbortWithStatusJSON(http.StatusInternalServerError, gin.H{"errmsg": err.Error()})
				return
			}
			c.JSON(http.StatusOK, mod)
		})
	}
}
