package server

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

	"github.com/gin-gonic/gin"

	"warpbox/lib/boxstore"
	"warpbox/lib/config"
	"warpbox/lib/metastore"
	"warpbox/lib/models"
)

func TestValidateManifestFileUploadRejectsExpiredBox(t *testing.T) {
	restoreUploadRoot := boxstore.UploadRoot()
	defer boxstore.SetUploadRoot(restoreUploadRoot)
	boxstore.SetUploadRoot(t.TempDir())

	boxID := "0123456789abcdef0123456789abcdef"
	if err := os.MkdirAll(boxstore.BoxPath(boxID), 0755); err != nil {
		t.Fatalf("MkdirAll returned error: %v", err)
	}
	manifest := models.BoxManifest{
		Files:     []models.BoxFile{{ID: "0123456789abcdef", Name: "file.txt", Status: models.FileStatusWait}},
		ExpiresAt: time.Now().UTC().Add(-time.Second),
	}
	if err := boxstore.WriteManifest(boxID, manifest); err != nil {
		t.Fatalf("WriteManifest returned error: %v", err)
	}

	app := &App{config: &config.Config{}}
	if err := app.validateManifestFileUpload(boxID, "0123456789abcdef", 1); err == nil {
		t.Fatal("expected expired box upload to be rejected")
	}
	if _, err := os.Stat(boxstore.BoxPath(boxID)); !os.IsNotExist(err) {
		t.Fatalf("expected expired box to be deleted, stat err=%v", err)
	}
}

func TestAdminProtectedPostRequiresCSRF(t *testing.T) {
	gin.SetMode(gin.TestMode)

	store, err := metastore.Open(t.TempDir())
	if err != nil {
		t.Fatalf("Open returned error: %v", err)
	}
	defer store.Close()

	adminTag, err := store.EnsureAdminTag()
	if err != nil {
		t.Fatalf("EnsureAdminTag returned error: %v", err)
	}
	user, err := store.CreateUserWithPassword("admin", "", "secret", []string{adminTag.ID})
	if err != nil {
		t.Fatalf("CreateUserWithPassword returned error: %v", err)
	}
	session, err := store.CreateSession(user.ID, time.Hour)
	if err != nil {
		t.Fatalf("CreateSession returned error: %v", err)
	}

	app := &App{config: &config.Config{}, store: store}
	router := gin.New()
	router.POST("/admin/test", app.requireAdminSession, func(ctx *gin.Context) {
		ctx.Status(http.StatusNoContent)
	})

	request := httptest.NewRequest(http.MethodPost, "/admin/test", nil)
	request.AddCookie(&http.Cookie{Name: adminSessionCookie, Value: session.Token})
	response := httptest.NewRecorder()
	router.ServeHTTP(response, request)
	if response.Code != http.StatusForbidden {
		t.Fatalf("expected missing CSRF token to be forbidden, got %d", response.Code)
	}
}
