package handlers

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

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

func TestSetDSMSResponseHeaders_NonEmptyCID_WritesAllHeaders(t *testing.T) {
	w := httptest.NewRecorder()
	c, _ := gin.CreateTestContext(w)

	setDSMSResponseHeaders(c, "bafytest123", "CE-Akte-FOO.pdf", 42)

	if got := w.Header().Get("X-DSMS-CID"); got != "bafytest123" {
		t.Errorf("X-DSMS-CID: want bafytest123, got %q", got)
	}
	if got := w.Header().Get("X-DSMS-Filename"); got != "CE-Akte-FOO.pdf" {
		t.Errorf("X-DSMS-Filename: want CE-Akte-FOO.pdf, got %q", got)
	}
	if got := w.Header().Get("X-DSMS-Size"); got != "42" {
		t.Errorf("X-DSMS-Size: want 42, got %q", got)
	}
	expose := w.Header().Get("Access-Control-Expose-Headers")
	if expose == "" {
		t.Error("Access-Control-Expose-Headers should be set so the browser surfaces the X-DSMS-* headers across same-origin proxies and CORS")
	}
	for _, h := range []string{"X-DSMS-CID", "X-DSMS-Filename", "X-DSMS-Size"} {
		if !contains(expose, h) {
			t.Errorf("Access-Control-Expose-Headers missing %s, got %q", h, expose)
		}
	}
}

func TestSetDSMSResponseHeaders_EmptyCID_WritesNothing(t *testing.T) {
	w := httptest.NewRecorder()
	c, _ := gin.CreateTestContext(w)

	setDSMSResponseHeaders(c, "", "irrelevant.pdf", 100)

	if got := w.Header().Get("X-DSMS-CID"); got != "" {
		t.Errorf("X-DSMS-CID should be absent for empty CID, got %q", got)
	}
	if got := w.Header().Get("X-DSMS-Filename"); got != "" {
		t.Errorf("X-DSMS-Filename should be absent for empty CID, got %q", got)
	}
	if got := w.Header().Get("X-DSMS-Size"); got != "" {
		t.Errorf("X-DSMS-Size should be absent for empty CID, got %q", got)
	}
}

func TestSetDSMSResponseHeaders_ZeroSize_StillWritesHeader(t *testing.T) {
	// A 0-byte archive is degenerate but valid — the frontend still needs the
	// CID badge to expose the chain to the user. Don't suppress the header.
	w := httptest.NewRecorder()
	c, _ := gin.CreateTestContext(w)

	setDSMSResponseHeaders(c, "bafyzero", "empty.pdf", 0)

	if got := w.Header().Get("X-DSMS-CID"); got != "bafyzero" {
		t.Errorf("X-DSMS-CID: want bafyzero, got %q", got)
	}
	if got := w.Header().Get("X-DSMS-Size"); got != "0" {
		t.Errorf("X-DSMS-Size: want 0, got %q", got)
	}
}

func contains(s, sub string) bool {
	for i := 0; i+len(sub) <= len(s); i++ {
		if s[i:i+len(sub)] == sub {
			return true
		}
	}
	return false
}
