package main

import (
	"net/http"

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

// requireSession is the standard auth shim every mutating handler wears.
// We don't store a shared service credential — the caller's X-Auth-Token
// is the only authority, and we probe PhotoPrism with it before doing any
// destructive work. The handler reads the validated token off the context
// via ctxToken so it can keep forwarding it to PhotoPrism for the actual
// operation.
func requireSession(pp *ppClient) gin.HandlerFunc {
	return func(c *gin.Context) {
		token := c.GetHeader("X-Auth-Token")
		if token == "" {
			c.AbortWithStatusJSON(http.StatusUnauthorized, gin.H{"error": "no token"})
			return
		}
		if !pp.validateSession(c.Request.Context(), token) {
			c.AbortWithStatusJSON(http.StatusUnauthorized, gin.H{"error": "invalid session"})
			return
		}
		c.Set("token", token)
		c.Next()
	}
}

// ctxToken returns the validated X-Auth-Token a previous requireSession
// middleware stored on the request. Handlers MUST run behind that
// middleware; otherwise this returns the empty string.
func ctxToken(c *gin.Context) string {
	v, ok := c.Get("token")
	if !ok {
		return ""
	}
	s, ok := v.(string)
	if !ok {
		return ""
	}
	return s
}
