package s3

import (
	"net/http"
	"testing"

	"wucher/internal/config"
)

func TestValidateConfig(t *testing.T) {
	valid := config.FileStorageConfig{
		Provider:              "s3",
		Bucket:                "wucher-file-dev",
		Region:                "ap-southeast-1",
		Endpoint:              "http://localhost:4566",
		AllowInsecureEndpoint: true,
	}

	if err := validateConfig(valid); err != nil {
		t.Fatalf("expected valid config, got %v", err)
	}

	invalidProvider := valid
	invalidProvider.Provider = "local"
	if err := validateConfig(invalidProvider); err == nil {
		t.Fatalf("expected invalid provider error")
	}

	missingBucket := valid
	missingBucket.Bucket = ""
	if err := validateConfig(missingBucket); err == nil {
		t.Fatalf("expected missing bucket error")
	}

	invalidEndpoint := valid
	invalidEndpoint.Endpoint = "://bad-url"
	if err := validateConfig(invalidEndpoint); err == nil {
		t.Fatalf("expected invalid endpoint error")
	}

	httpEndpointBlocked := valid
	httpEndpointBlocked.AllowInsecureEndpoint = false
	if err := validateConfig(httpEndpointBlocked); err == nil {
		t.Fatalf("expected insecure endpoint error")
	}
}

func TestBuildObjectKey(t *testing.T) {
	if got := buildObjectKey("fm/objects", "abc/123"); got != "fm/objects/abc/123" {
		t.Fatalf("unexpected key: %q", got)
	}
	if got := buildObjectKey("fm/objects/", "/abc/123"); got != "fm/objects/abc/123" {
		t.Fatalf("unexpected key with slashes: %q", got)
	}
	if got := buildObjectKey("fm/objects", "fm/objects/abc/123"); got != "fm/objects/abc/123" {
		t.Fatalf("unexpected key with existing prefix: %q", got)
	}
	if got := buildObjectKey("", "abc/123"); got != "abc/123" {
		t.Fatalf("unexpected key without prefix: %q", got)
	}
}

func TestCanonicalSignedHeaders(t *testing.T) {
	headers := http.Header{
		"Content-Type": []string{"application/pdf"},
		"X-Amz-Date":   []string{"20260405T000000Z"},
	}

	got := canonicalSignedHeaders(headers)
	if got["content-type"] != "application/pdf" {
		t.Fatalf("unexpected content-type header: %q", got["content-type"])
	}
	if got["x-amz-date"] != "20260405T000000Z" {
		t.Fatalf("unexpected x-amz-date header: %q", got["x-amz-date"])
	}
}
