package server

import (
	"os"
	"testing"
	"time"

	"warpbox/lib/boxstore"
	"warpbox/lib/config"
	"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)
	}
}
