package router

import (
	"encoding/json"
	"net/http"
	"net/http/httptest"
	"os"
	"path/filepath"
	"testing"

	"github.com/gofiber/fiber/v3"
)

func TestSwaggerJSONUsesRequestOrigin(t *testing.T) {
	app := fiber.New()
	SetupRoutes(app)

	req := httptest.NewRequest(http.MethodGet, "/docs/swagger.json", nil)
	resp, err := app.Test(req)
	if err != nil {
		t.Fatalf("request failed: %v", err)
	}
	t.Cleanup(func() {
		_ = resp.Body.Close()
	})

	if resp.StatusCode != http.StatusOK {
		t.Fatalf("expected status %d, got %d", http.StatusOK, resp.StatusCode)
	}

	var spec map[string]any
	if err := json.NewDecoder(resp.Body).Decode(&spec); err != nil {
		t.Fatalf("failed to decode swagger json: %v", err)
	}

	if _, ok := spec["host"]; ok {
		t.Fatal("swagger spec should not expose a fixed host")
	}

	if _, ok := spec["schemes"]; ok {
		t.Fatal("swagger spec should not expose fixed schemes")
	}
}

func TestUploadsAreServedStatically(t *testing.T) {
	app := fiber.New()
	SetupRoutes(app)

	if err := os.MkdirAll("uploads", 0755); err != nil {
		t.Fatalf("failed to create uploads dir: %v", err)
	}

	filename := "router-static-test.txt"
	filePath := filepath.Join("uploads", filename)
	if err := os.WriteFile(filePath, []byte("hello-image"), 0644); err != nil {
		t.Fatalf("failed to write test file: %v", err)
	}
	t.Cleanup(func() {
		_ = os.Remove(filePath)
	})

	req := httptest.NewRequest(http.MethodGet, "/uploads/"+filename, nil)
	resp, err := app.Test(req)
	if err != nil {
		t.Fatalf("request failed: %v", err)
	}
	t.Cleanup(func() {
		_ = resp.Body.Close()
	})

	if resp.StatusCode != http.StatusOK {
		t.Fatalf("expected status %d, got %d", http.StatusOK, resp.StatusCode)
	}
}
