// GoToSocial
// Copyright (C) GoToSocial Authors admin@gotosocial.org
// SPDX-License-Identifier: AGPL-3.0-or-later
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU Affero General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
// GNU Affero General Public License for more details.
//
// You should have received a copy of the GNU Affero General Public License
// along with this program.  If not, see <http://www.gnu.org/licenses/>.

package middleware

import (
	"context"
	"time"

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

// Timeout provides gin middleware that times out
// the request context after the given duration.
func Timeout(timeout time.Duration) gin.HandlerFunc {
	if timeout <= 0 {
		return nil
	}
	return func(c *gin.Context) {
		if upgr := c.GetHeader("Upgrade"); upgr != "" {
			// Upgrade to wss (probably).
			// Leave well enough alone.
			c.Next()
			return
		}

		// Wrap request context with timeout.
		ctx, cancel := context.WithTimeout(
			c.Request.Context(),
			timeout,
		)
		defer cancel()

		// Update request context with timeout.
		c.Request = c.Request.WithContext(ctx)

		// Process
		// request!
		c.Next()
	}
}
