package middleware

import (
	"context"
	"net/http"

	"github.com/ultisuite/ulti-backend/internal/api/apiresponse"
	"github.com/ultisuite/ulti-backend/internal/apitokens"
)

// MailScopeAccountIDs returns nil when all mail accounts are allowed (session or token),
// otherwise the explicit account IDs authorized by the API token.
func MailScopeAccountIDs(ctx context.Context) []string {
	auth := ApiTokenFromContext(ctx)
	if auth == nil || auth.MailScope.AllAccounts {
		return nil
	}
	return auth.MailScope.AccountIDs
}

func DenyIfMailAccountOutOfScope(w http.ResponseWriter, r *http.Request, accountID string) bool {
	auth := ApiTokenFromContext(r.Context())
	if auth == nil || accountID == "" {
		return false
	}
	if apitokens.AllowsMailAccount(auth, accountID) {
		return false
	}
	apiresponse.WriteError(w, r, http.StatusForbidden, apiresponse.CodeAuthForbidden, "mail account out of token scope", nil)
	return true
}

func DenyIfDrivePathOutOfScope(w http.ResponseWriter, r *http.Request, paths ...string) bool {
	auth := ApiTokenFromContext(r.Context())
	if auth == nil {
		return false
	}
	for _, p := range paths {
		if p == "" {
			continue
		}
		if !apitokens.AllowsDrivePath(auth, p) {
			apiresponse.WriteError(w, r, http.StatusForbidden, apiresponse.CodeAuthForbidden, "drive path out of token scope", nil)
			return true
		}
	}
	return false
}
