package api

import (
	"log"
	"net/http"
	"os"
	"path"
	"strconv"

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

var (
	Simulator    string
	TeamsDir     string
	ManagerUsers []string
)

func authMiddleware(access ...func(string, int64, *gin.Context) bool) gin.HandlerFunc {
	return func(c *gin.Context) {
		ficteam := Simulator
		if t := c.Request.Header.Get("X-FIC-Team"); t != "" {
			ficteam = t
		}

		var teamid int64
		var err error

		if ficteam == "" {
			c.AbortWithStatusJSON(http.StatusUnauthorized, gin.H{"errmsg": "Need to authenticate"})
			return
		} else if teamid, err = strconv.ParseInt(ficteam, 10, 64); err != nil {
			if lnk, err := os.Readlink(path.Join(TeamsDir, ficteam)); err != nil {
				log.Printf("[ERR] Unable to readlink %q: %s\n", path.Join(TeamsDir, ficteam), err)
				c.AbortWithStatusJSON(http.StatusInternalServerError, gin.H{"errmsg": "Unable to validate authentication."})
				return
			} else if teamid, err = strconv.ParseInt(lnk, 10, 64); err != nil {
				log.Printf("[ERR] Error during ParseInt team %q: %s\n", lnk, err)
				c.AbortWithStatusJSON(http.StatusInternalServerError, gin.H{"errmsg": "Unable to validate authentication."})
				return
			}
		}

		// Check access limitation
		for _, a := range access {
			if !a(ficteam, teamid, c) {
				return
			}
		}

		// Retrieve corresponding user
		c.Set("LoggedUser", ficteam)
		c.Set("LoggedTeam", teamid)

		// We are now ready to continue

		c.Next()
	}
}
