package middleware

import (
	"net/http"
	"net/http/httptest"
	"testing"
	"time"

	"github.com/gofiber/fiber/v2"

	"wucher/internal/service"
	"wucher/internal/shared/pkg/uuidv7"
)

func TestWOPIRequiredAcceptsTokenFromWOPISrc(t *testing.T) {
	fileID := uuidv7.MustBytes()
	userID := uuidv7.MustBytes()
	wopiSvc := service.NewWOPIService(service.WOPIConfig{
		TokenSecret:   "test-secret",
		PublicBaseURL: "https://api.example.com",
		TokenTTL:      30 * time.Minute,
	})
	token, _, err := wopiSvc.MintAccessToken(fileID, userID, nil, service.WOPIPermissionWrite)
	if err != nil {
		t.Fatalf("mint access token: %v", err)
	}

	app := fiber.New()
	app.Use(WOPIRequired(wopiSvc))
	app.Get("/wopi/files/:fileId", func(c *fiber.Ctx) error {
		return c.SendStatus(http.StatusOK)
	})

	fileIDString, err := uuidv7.BytesToString(fileID)
	if err != nil {
		t.Fatalf("file id string: %v", err)
	}
	req := httptest.NewRequest(http.MethodGet, "/wopi/files/"+fileIDString+"?WOPISrc=https%3A%2F%2Fapi.example.com%2Fwopi%2Ffiles%2F"+fileIDString+"%3Faccess_token%3D"+token, nil)
	resp, err := app.Test(req)
	if err != nil {
		t.Fatalf("app test failed: %v", err)
	}
	if resp.StatusCode != http.StatusOK {
		t.Fatalf("unexpected status %d", resp.StatusCode)
	}
}
